Hello! I made my own validation attribute, which is inherited from ValidationAttribute , redefined the IsValid(object value, ValidationContext validationContext) method IsValid(object value, ValidationContext validationContext) and set the attribute to the Login property in the RegisterModel class. All the basic attributes of validation work fine, but this one is not. 0 results - validation does not work in forms, only from built-in attributes. Even the stopping points don't work. The method itself checks if a user exists with such a login.

Attribute class code:

 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public sealed class UniqueLoginAttribute : ValidationAttribute { Context Context = new Context(); // База данных (Entity Framework) public UniqueLoginAttribute(string Error) { ErrorMessage = Error; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { string temp = value.ToString().ToLower(); if (Context.Users.Where(x => x.Login.ToLower() == temp).Count() == 0) return ValidationResult.Success; return new ValidationResult(ErrorMessage); } } 

Login field code:

  [Required(ErrorMessage = "Обов'язкове поле")] [DisplayName("Логін")] [MinLength(5, ErrorMessage = "Логін повинен містити не менше 5 символів.")] [MaxLength(14, ErrorMessage = "Логін повинен містити не більше 14 символів.")] [RegularExpression(@"^[a-zA-Z0-9]+$", ErrorMessage = "Логін повинен містити тільки букви латинського алфавіту і цифри.")] [UniqueLogin("Користувач з заданим логіном вже зареєстрований!")] public string Login { get; set; } 
  • The code should be applied with text, not pictures. - Egor Trutnev
  • @EgorTrutnev right now - Vlad
  • @Vlad in this implementation, the work of your attribute can be checked in debug only if the model passed the test on the client and went to the server. Are you sure that you have no errors on the client? - null

1 answer 1

Are you sure you have no build bugs? Missing breakpoints indicate this problem. I compiled and executed your attribute without any problems - it was called and executed correctly. One thing to remember: the method in your controller will still be executed, even if your check fails, you need to check ModelState.IsValid .

Controller:

 [HttpPost] public ActionResult Create(EmployeeModel um) { if (!ModelState.IsValid) { ViewBag.updateError = "Update Failure"; } else { //.... } return View(um); }