How do I use IValidatableObject?

前端 未结 7 1816
我在风中等你
我在风中等你 2020-11-22 02:59

I understand that IValidatableObject is used to validate an object in a way that lets one compare properties against each other.

I\'d still like to have

7条回答
  •  难免孤独
    2020-11-22 03:36

    The thing i don't like about iValidate is it seems to only run AFTER all other validation.
    Additionally, at least in our site, it would run again during a save attempt. I would suggest you simply create a function and place all your validation code in that. Alternately for websites, you could have your "special" validation in the controller after the model is created. Example:

     public ActionResult Update([DataSourceRequest] DataSourceRequest request, [Bind(Exclude = "Terminal")] Driver driver)
        {
    
            if (db.Drivers.Where(m => m.IDNumber == driver.IDNumber && m.ID != driver.ID).Any())
            {
                ModelState.AddModelError("Update", string.Format("ID # '{0}' is already in use", driver.IDNumber));
            }
            if (db.Drivers.Where(d => d.CarrierID == driver.CarrierID
                                    && d.FirstName.Equals(driver.FirstName, StringComparison.CurrentCultureIgnoreCase)
                                    && d.LastName.Equals(driver.LastName, StringComparison.CurrentCultureIgnoreCase)
                                    && (driver.ID == 0 || d.ID != driver.ID)).Any())
            {
                ModelState.AddModelError("Update", "Driver already exists for this carrier");
            }
    
            if (ModelState.IsValid)
            {
                try
                {
    

提交回复
热议问题