.net MVC Validation with Data Annotation


With MVC you can validate data in the UI and before sending to the database auto-magically if you add Data Annaotation Validators to your model classes. Here are some of the more commonly used validators and samples on how to use them.

Add using System.ComponentModel.DataAnnotations; to your model.

[Required] – States the field is required

sample :
[Required( AllowEmptyStrings=false,ErrorMessage=”You must eneter a name”)]
public string Name { get; set; }

[StringLength] – Used to set min and max string length.

sample:
[StringLength (20,MinimumLength=5,ErrorMessage=”Name must be between 5 and 20 characters”)]

[MaxLength] – Max length of a string

sample:
[MaxLength(20,ErrorMessage=”Name must be less than 20 Characters”);
public string Name { get; set; }

[MinLength] – minimum length of a string

sample:
[MinLength (5,ErrorMessage=”Name must be more than 5 characters”)]
public string Name { get; set; }

[Range] – States the value of a number must be between x and y.

sample:
[Range (1,99,ErrorMessage=”Age must be between 1 and 99″)]
public int age {get;set;}

[RegularExpression] – Used to validate the format of a string

sample:
[RegularExpression(“[a-z0-9!#$%&’*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&’*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?”, ErrorMessage=”Invalid Email Address”)]
public string Email { get; set; }

[PropertiesMustMatch] – Class level attribute used to validate something like Password1 = Password2.

sample:
[PropertiesMustMatch(“Password”, “ConfirmPassword”, ErrorMessage = “The password and confirmation password do not match.”)]
public class user {

public string name {get;set;}

public string Password {get;set;}

public string ConfirmPassword {get;set;}

}

Advertisements

About Kevin Buckley
.Net web developer with a lot of experience in CMS. Currently working at Sitecore as Solutions Engineer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: