Types of Validation in MVC

Default validation:

The model binder maps request data to model classes and, in doing so, it validates input values against validation attributes set on the model class. Validation occurs through a provider. The default validation provider is based on data annotations. The default validation provider is [csharp]DataAnnotationsModelValidatorProvider[/csharp] class.

Cross-property validation:

The data annotations we’ve considered so far are attributes you use to validate the content of a single field. This is useful, but it doesn’t help that much in a real-world scenario in which you likely need to validate the content of the property in light of the value stored in another. Cross-property validation requires a bit of context-specific code.

public ActionResult Edit(MemoDocument memo)
{
if (ModelState.IsValid)
{
// If here, then properties have been individually validated.
// Proceed with cross-property validation and merge model-state dictionary
// to reflect feedback to the UI.
...
}
}

Custom Validation:

The CustomValidation attribute forces you to validate the value stored in the property without the possibility of adding any extra parameters.

[AttributeUsage(AttributeTargets.Property)]
public class EvenNumberAttribute : ValidationAttribute
{
public Boolean MultipleOf4 { get; set; }
public override Boolean IsValid(Object value)
{
if (value == null)
return false;
var x = -1;
try
{
x = (Int32) value;
}
catch
{
return false;
}
if (x % 2 > 0)
return false;
if (!MultipleOf4)
return true;
// Is a multiple of 4?
return (x % 4 == 0);
}
}

Client-Side validation:

When you turn on client-side validation, all built-in data annotation attributes gain a client-side behaviour and, to the extent that it is possible, perform their validation in JavaScript within the browser. If the validation fails, no request is made to the web server.

Self-validation:

Data annotations attempt to automate the validation process around data being posted from forms. Most of the time, you use only stock attributes and get error messages for free. In ASP.NET MVC, you can always access the entire model via the validation context; however, ultimately, when the validation is complex, many developers prefer to opt for a handcrafted validation layer.

In other words, you stop fragmenting validation in myriad combinations of data annotations and move everything into a single place.

public ActionResult Edit(MemoDocument memo)
{
if (!Validate(memo))
ModelState.AddModelError(...);
...
}