To enable client side validation and unobtrusive validation we need to provide settings in web.config or in server side HtmlHelper.
If jquery unobtrusive library is referenced in cshtml then there do not need to write any custom code to validate form with the help of data annotation validation attribute.
When this code will be executed the form can be validated automatically by jquery unobtrusive validation.
When you enable unobtrusive validation ASP.NET MVC add data attribute in HTML for each data annotation.
In HTML attributes are generated for data annotation in server side and jquery unobtrusive library parsed those attribute for client validation.
But what will happen if validation on any field depends on the value of another field value. You may also want this validation not only client side but also in server side. Usually in such case we write custom validation before submitting form and also do same validation in server side. We can also do same custom validation using Data annotation and jquery unobtrusive validation without directly referencing client control.
Suppose the requirement is to validate Email field as required only if Name field is not empty. So if Name field is not empty then we do not have to provide Email.
It this case the server side validation would be not difficult. We can create an data annotation attribute which will make decision based on value of Name property.
This is not final code.
In this code a custom validation attribute is created. IsValid() function gets the value of Name field and make decision based on Name value. Attribute on Email property can be defined as:
Here Name is the property on which validation depends and also sets another value to determine validation logic is required or not. But this validation works only on server side and in the HTML code no such validation attribute is created.
To make this validation work also on client side some Html attribute need to be created and make jquery unobtrusive library understand those attribute. To create those html attribute our custom attribute class need to be implemented by IClientValidatable interface. If class is implemented by IClientValidatable interface, method name GetClientValidationRules() can be implemented to define the rules that will be generate as html attribute.
We need to define such rule in unobtrusive adapter so that client side validation understand these html attribute. unobtrusive adapter gives option to define method which will work with such rules and defined data attribute.
Here same validation is defined as server side code. When the save button will be clicked the form will be be validate and it will call this method. Client side validation provides same validation with error message defined in server side. Such validation can be used for multiple controls as that does not depend on any HTML control.