Tuesday, July 14, 2015

Custome validations in MVC

Validations are very important in any application  and Validations restrict the invalid data being entered into the application.

In MVC we can build a custom validations framework by extending “ValidationAttribute”, “IClientValidatable”.

 

The “ValidationAttribute“ class serves as base class for all  validations  and  By overriding “Isvalid” method we can  extend the validations.

The ValidateAttribute take two parameters value and the Validation context which holds all the control values.

 

For example I want to compare   two dates.

 

Create a class with extends the validation attribute and create a property of compare to date field name. using validation Context, retrieve the value the compare to date field value and then

Compare with Self value .

 public class GreaterDateAttribute : ValidationAttribute

{

 

  public string EarlierDateField { get; set; }

 

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)

        {

            DateTime? date = value != null ? (DateTime?)value : null;

            var earlierDateValue = validationContext.ObjectType.GetProperty(EarlierDateField)

                .GetValue(validationContext.ObjectInstance, null);

            DateTime? earlierDate = earlierDateValue != null ? (DateTime?)earlierDateValue : null;

 

            if (date.HasValue && earlierDate.HasValue && date < earlierDate)

            {

                return new ValidationResult(ErrorMessage);

            }

 

            return ValidationResult.Success;

        }

}

Regular expression for validating file name ends with .doc or docx or pdf

Expression:  ^.+\.(?:(?:[dD][oO][cC][xX]?)|(?:[pP][dD][fF]))$

Explanation:

                   ^           = beginning of string

                   .+          = at least one character (any character)

                  \.            = dot ('.')

                (?:pattern) = match the pattern without storing the match)

                [dD]        = any character in the set ('d' or 'D')

                [xX]?       = any character in the set or none

              ('x' may be missing so 'doc' or 'docx' are both accepted)

                  |           = either the previous or the next pattern

                   $          = end of matched string