There are many types of validations that do allow in MVC Models such like Required Field Validator, Data Type Validator, Range Validator and etc… But there is a way that the developer can write his own Validation Rules and work with them as a normal validator that comes built-in. This is way far easier in MVC.
First Create a New MVC 3 Application. Create a new class in the Model or can use the existing one as well. Add a reference toSystem.ComponentModel.DataAnnotations.
1
| using System.ComponentModel.DataAnnotations; |
In this case, I am going to use as sample model named User for the validation.
1
2
3
4
5
6
7
8
9
10
| public class User { public int UserID; public string Gender; public string Salution; public string UserName; public string FirstName; public string LastName; public DateTime RegistrationTime; } |
I do need to validate the inputs{“Male” or “Female”} for Gender of the User and I would like to name that controller as GenderValidation.
Here comes the action.
Define a class named GenderValidationAttribute that inherits from ValidationAttribute. Then override the method IsValid from the Base class.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| public class GenderValidationAttribute : ValidationAttribute { protected override ValidationResult IsValid( object value, ValidationContext validationContext) { string gender = value.ToString(); if (!(value.Equals( "Male" ) | value.Equals( "Female" ))) { return new ValidationResult( "Invalid Input for Gender." ); } return ValidationResult.Success; } } |
Now this can be used as normal as a general Validation Attribute. Change the User Model like below.
1
2
3
4
5
6
7
8
9
10
11
| public class User { public int UserID; [GenderValidation] public string Gender; public string Salution; public string UserName; public string FirstName; public string LastName; public DateTime RegistrationTime; } |
Informative source code is given to solve such problems as all this depends on a good asp.net developer.
ReplyDelete