Tuesday, June 3, 2014

Data Annotation

Questions and Answers on Data Annotation

What is data annotation:
Declarative style of validation. It also provides meta data to Framework - which is helpful in building HTML.

What is @EditForModel helper?
The EditorForModel helper builds out editors for every property in a model object.

What is the namespace of Data annotation?
System.ComponentModel.DataAnnotations.

What is validation attributes.
They generates validation logic on both server side and client side.

What is Required attribute?
It enforces user to provide some value.

What is StringLength attribute?
It enforces length criteria for a field.

Examples of other validation attributes:
         [StringLength(50, MinimumLength=3)]
         [RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]
         [Range(1,100)]
         [Range(typeof(decimal), "0.00", "49.99")]


Validation Attributes from System.Web.Mvc
The Remote attribute enables you to perform client-side validation with a server callback.
The Compare attribute enables you to compare two controls.

Example for Remote: To check email duplication.

[Remote("ActionName", "Controller")]
public string email;

public JsonResult CheckEmail(string email)
{
     var result = Business.FindEmail(email).Count == 0;
     return Json(result, JsonRequestBehavior.AllowGet);
}

1. [Compare("Email")]
    public string EmailConfirm { get; set; }

Custom Validators:
Two ways to achieve:
    1. Custom Data Annotation: For easy reuse, but should be programmed accordingly.
    2. Model specific: For easy programmability. Achieved by implementing IValidatableObject interface.

Example of Custom Data Annotation:

using System.ComponentModel.DataAnnotations;
public class OnlcyNumbers : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
     // Logic for validation
 return ValidationResult.Success;
}
}