Creating custom data annotation validation in MVC 3

前端 未结 4 956
说谎
说谎 2020-12-16 05:15

For instance, I have an Employee view model. When creating an employee, I want to validate the username to make sure it doesn\'t exist.

public class Employee         


        
4条回答
  •  旧时难觅i
    2020-12-16 05:37

    You can write your own custom validation as explained here. I've modified the code to add validation in the model as I prefer rails active record's validation style in the model.

    public class EmployeeViewModel
    {
    
        [CustomValidation(typeof(EmployeeViewModel), "ValidateDuplicate")]
        [Required(ErrorMessage = "Username is required")]
        [DisplayName("Username")]
        public string Username { get; set; }
    
        public static ValidationResult ValidateDuplicate(string username)
        {
          bool isValid;
    
          using(var db = new YourContextName) {
            if(db.EmployeeViewModel.Where(e => e.Username.Equals(username)).Count() > 0)
           {
              isValid = false;
           } else {
              isValid = true;
           }
          }
    
          if (isValid)
          {
            return ValidationResult.Success;
          }
          else
          {
            return new ValidationResult("Username already exists");
          }
    
        }
    }
    

提交回复
热议问题