Validation in ASP.NET MVC Razor view

ASP.NET MVC uses DataAnnotations attributes to implement validations. DataAnnotations includes built-in validation attributes for different validation rules, which can be applied to the properties of model class. ASP.NET MVC framework will automatically enforce these validation rules and display validation messages in the view

The following table lists DataAnnotations validation attributes.

Attribute Description
Required Indicates that the property is a required field
StringLength Defines a maximum length for string field
CreditCard Specifies that the specified field is a credit card number
Phone Specifies that the field is a phone number using regular expression for phone numbers
MinLength Specifies minimum length for a string field
MaxLength Specifies maximum length for a string field
FileExtension Validates with file extension
EmailAddress Validates with email address format
CustomValidation Specified custom validation method to validate the field
RegularExpression Specifies that the field value must match with specified Regular Expression
Range Defines a maximum and minimum value for a numeric field

DataAnnotations attributes included can be used with namespace

 System.ComponentModel.DataAnnotations;
Model validation :

public int id { get; set; }

[Required(ErrorMessage=”Name is required ?“)]
public string name { get; set; }

[Required(ErrorMessage=”Password Required ?“)]
[StringLength(50,ErrorMessage=”password are 10 char ?“,MinimumLength=7)]
[Display(Name=”password“)]
[DataType(DataType.Password)]
public string password { get; set; }

[Required(ErrorMessage = “Password Required ?“)]
[StringLength(50, ErrorMessage = “password 10 char“, MinimumLength = 7)]
[Compare(“password“,ErrorMessage=”pasword not match try again ?“)]
public string cpassword { get; set; }

public string gender { get; set; }
public string subject { get; set; }

[Required(ErrorMessage = “Nomber is required ?“)]
[StringLength(50, ErrorMessage = “password r 10 char“, MinimumLength = 10)]
public string number { get; set; }

[Required(ErrorMessage = “Please Enter Email Address“)]
[RegularExpression(“.+@.+\\..+”, ErrorMessage = “Please Enter Correct Email Addres“)]
public string email { get; set; }

public string city { get; set; }

View Validation result with razor view

 

Validation in ASP.NET MVC Razor view

SEE MORE

20 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *