MVC Validation- Custom Server and Client Side

Server Side Validation :

MVC Provides custom validation  via ValidationAttribute and IValidatableObject.

Server Side Validation with ValidationAttribute :

To implement custom server side validation,we must inherit from ValidationAttribute. In the below sample,i have a custom validator that checks if date is greater than todays date.


public class ValidateDate : ValidationAttribute
{
public ValidateDate()
{
ErrorMessage = "Date Time Cannot be greater than today's date";
}
public override bool IsValid(object value)
{
var datetime = Convert.ToDateTime(value);
if (datetime > DateTime.Now)
{
return false;
}
return true;
}

}

Usage : To use the above attribute,its enough to annotate over the property.


public class SampleModel
{
[Required]
[ValidateDate] //-----Custom Validator------//
public DateTime StartdateTime { get; set; }
}

As you can see above the validation works only after post back(after submit button) and the validation happens in server side.

Handling Custom Validation from Client Side :

Apart from javascript validation over model,mvc also provides custom validation from client side.

Implementing custom client side validation :

IClientValidatable interface indicates the mvc framework that the cutom validator supports client side validation. It provides a contract named  IEnumerable<ModelClientValidationRule> GetClientValidationRules that is responsible for returning validation rules in client side.

In the code below is the custom client side validator that implements IClientValidatable interface which displays an error message when date is greater than today’s date.


[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
 public class ValidateDate : ValidationAttribute,IClientValidatable
 {
 public ValidateDate()
 {
 ErrorMessage = "Date Time Cannot be greater than today's date";
 }
 public override bool IsValid(object value)
 {
 var datetime = Convert.ToDateTime(value);
 if (datetime &gt; DateTime.Now)
 {
 return false;
 }
 return true;
 }

public IEnumerable&lt;ModelClientValidationRule&gt; GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
 {
 var modelvalidtorrule = new ModelClientValidationRule();
 modelvalidtorrule.ValidationType = "dategreaterthan"; //---will be used in registering with jquery adaptor---//
 modelvalidtorrule.ErrorMessage = ErrorMessage;
 return new[] {modelvalidtorrule};
 }
 }

Registering the Custom Validator with Jquery Adaptor :

Inorder to achieve the client side validation,we must add and register to jquery validator and adapters. 

Adding custom validator to Jquery Validator :


jQuery.validator.addMethod('dategreaterthan', function (value, element, params) {
 var currentDate = new Date();
 if (Date.parse(value) &gt; currentDate) {
 return false;
 }
 return true;
 }, '');

Adding custom Validator to Jquery Adaptor :


jQuery.validator.unobtrusive.adapters.add('dategreaterthan', function (options) {
options.rules['dategreaterthan'] = {};
options.messages['dategreaterthan'] = options.message;
});

Capture

 

 

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