Techbubbles

Validation Components in ASP.NET MVC

Validating the user input and showing a user-friendly error message is an important step in Web Application development. ASP.NET MVC framework provides validation features which helps developer to validate model values. The validation features in MVC allows you to write the validation using attributes which is called data annotations. This post outlines the data annotation features that you can use in ASP.NET MVC application development.Data Annotations attributes can find in System.ComponentModel.DataAnnotations namespace.

Common Validations

You can use Required attribute on the model class properties to check whether the property value is null or empty. The model class with required attribute looks as below

public class Product
    {
        public virtual int ProductId { get; set; }
        public virtual int ProductCategoryId { get; set; }
        [Required]
        public virtual string ProductName { get; set; }
        [Required]
        public virtual decimal Price { get; set; }
        public virtual string color { get; set; }
        public virtual ProductCategory ProductCategory { get; set; }
    }

If you submit the form without entering the required field value then you will see the below error message in web page

image

If you want to limit the number of character that user input for a particular string field then you can use StringLength attribute as shown below

[Required]
[StringLength(200, MinimumLength=3)]
 public virtual string ProductName { get; set; }

MinimumLength is an optional parameter which you can use for specifying minimum length for property value.

Range

Range attribute specifies a minimum and maximum values for a numerical value property. Example

[Range(25,64)]
public int Age {get; set}

RegularExpressions

You can also use RegularExpressions on model properties for example on Email

[RegularExpression(@" [A-Za-z0-9._%+-]+@[A-Za-z0-9.-] + \. [A-Za-z] {2,4} " )]
public string Email {get; set;}
[Range(typeof(decimal), "0.00", "33.66" ]
public decimal price {get; set;}

Remote

This attribute is available in System.Web.Mvc namespace. Remote attribute works on client-side with a call-back to the server. For example in-order to validate the UserName property in your application you can write code something like below

[Remote("ValidateUserName", "Account" )]
public string UserName {get; set; }

Inside the attribute you have to specify the name of the action method and name of the controller that client code should call.

public JsonResult ValidateUserName(string username)
{
     //Write the logic here
}

Custom Error Message

Every attribute specified above allows you to pass a named parameter with a custom error message. For example

[Required(ErrorMessage="Product Name is required")]
[StringLength(200)]
 public virtual string ProductName { get; set; }

Localization support is also there to display the error message to users. You can specify resource type and resource name for error messages.

[Required(ErrorMessageResourceType=typeof(Messages),      ErrorMessageResourceName="ProductNameRequired")]
[StringLength(200)]
public virtual string ProductName { get; set; }

Messages is a resource file and ProductNameRequired is an entry in it.

MVC Framework executes the validation logic during the Model binding. You can find all failed validation rules in model state.

Related Posts:

%d bloggers like this: