Creating a custom data annotation check in MVC 3

For example, I have an Employee view model. When creating an employee, I want to check the username to make sure that it does not exist.

public class EmployeeViewModel { [ScaffoldColumn(false)] public int EmployeeId { get; set; } [ValidateDuplicate(ErrorMessage = "That username already exists")] [Required(ErrorMessage = "Username is required")] [DisplayName("Username")] public string Username { get; set; } } 

And then I have a ValidateDuplicate function somewhere with code to check for duplicate.

Is it possible?

+6
source share
4 answers

I would suggest looking at the remote check. An example even matches your case.

Basically, add the remote attribute to the viewmodel property, which indicates the action of the controller

 [Remote("IsUserExists", "Account", ErrorMessage = "Can't add what already exists!")] [Required(ErrorMessage = "Username is required")] [DisplayName("Username")] public string Username { get; set; } 

which does your work

 public ActionResult IsUserExists(string userName) { if (!UserService.UserNameExists(userName) || (CurrentUser.UserName == userName)) { return "Ok."; } } 
+14
source

Yes it is possible. You need to write your own validation attribute .

+2
source

You can write your own check as described here . I changed the code to add validation to the model, as I prefer the style of checking active rail activity 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"); } } } 
+2
source

You can do this by extending the Attribute class by calling it ValidateDuplicate. I would avoid doing it like this because it is just another place where you potentially need to call the database.

0
source

Source: https://habr.com/ru/post/891676/


All Articles