Server side validation should be always enabled and stronger than the client side validation. Some things could be difficult to validate on the client side, like complex interactions between the models or the model properties.
However, you can do client validation using the jQuery
validator plugin (which comes with the VS MVC project templates).
You have your validation attribute on the server, which implements IClientValidatable
:
public class MyValidationAttribute : ValidationAttribute, IClientValidatable
{
public override bool IsValid(object value)
{
if (value == null) {
return true;
}
//Add validation rules
if (false) {
return false;
}
return true;
}
public override string FormatErrorMessage(string name)
{
return "Please provide valid values."
}
public IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, System.Web.Mvc.ControllerContext context)
{
return new ModelClientValidationRule[] { new ModelClientValidationRule {
ErrorMessage = "Please provide valid values.",
ValidationType = "validationrule"
} };
}
}
On the client side, you will need to add the validation rule:
jQuery.validator.addMethod("validationrule", function (value, element, param) {
if (value == "") {
return false;
}
return true;
});
jQuery.validator.unobtrusive.adapters.addBool('validationrule');
Make sure you add this outside the jQuery ready handler. See the accepted answer for this question.