This blog is useful to all my friends who are working on the .Net Technology and wants to enhance their skills as well their problem solving ability.

Thursday, April 25, 2013

Adding your Custom validation in MVC 4 using Validation Attribute and unobtrusive Jquery library


1)  DEFINED YOUR PROPERTY IN MODEL CLASS ....

//DefaultReorderQuantity
        [Display(Name = "DefaultReorderQuantity", ResourceType = typeof(ResItemMaster))]
        [RegularExpression(@"^[0-9\.]*$", ErrorMessageResourceName = "InvalidValue", ErrorMessageResourceType = typeof(ResMessage))]
        [Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ResMessage))]
        [DefaultReorderQuantityCheck("MaximumQuantity", ErrorMessage = "Default Reorder quantity must be less then Maximum quantity")]
        public System.Double DefaultReorderQuantity { get; set; }

 2) IN MODEL CREATE NEW CLASS WITH SAME NAME OF PROPERTY

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class DefaultReorderQuantityCheckAttribute : ValidationAttribute, IClientValidatable
{
    private readonly string _MaxQTYFieldName;
    public DefaultReorderQuantityCheckAttribute(string MaxQtyFieldName)
    {
        _MaxQTYFieldName = MaxQtyFieldName;
    }
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var property = validationContext.ObjectType.GetProperty(_MaxQTYFieldName);
        var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null);
        if (value != null)
        {
            double DefReQTY = (double)value;
            if (DefReQTY >= (double)otherPropertyValue)
            {
                ValidationResult Ok = new ValidationResult("Default Reorder quantity must be less then Maximum quantity");
                return Ok;
            }
        }
        return ValidationResult.Success;
    }
    public IEnumerable
           GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule
        {
            ErrorMessage = ErrorMessage,
            ValidationType = "defaultreorderquantity"
        };
    }
}



3)  IN YOUR VIEW ADD THIS LINES TO CHECK VALIDATION FROM CLIENT SIDE

$("form").submit(function (e) {
        $.validator.unobtrusive.parse("#frmItemMaster");
       
        if ($(this).valid()) {
                   }
        e.preventDefault();
    });   


4) ADD BELOW LINES TO ADD THE RULE OF VALIDATION IN unobtrusive  VALIDATION LIBRARY ....

jQuery.validator.addMethod('defaultreorderquantity', function (value, element, params) {
            if (parseInt(element.form.DefaultReorderQuantity.value == '' ? 0 : element.form.DefaultReorderQuantity.value, 10) >= parseInt(element.form.MaximumQuantity.value == '' ? 0 : element.form.MaximumQuantity.value, 10))
                return false;
            else
                return true;
        }, '');
        jQuery.validator.unobtrusive.adapters.add('defaultreorderquantity', {}, function (options) {
            options.rules['defaultreorderquantity'] = true;
            options.messages['defaultreorderquantity'] = options.message;
        });

5 ) CONTROLLER SIDE VALIDATION IF REQUIRED

if (!ModelState.IsValid)
            {
if (ModelState["DefaultReorderQuantity"].Errors.Count > 0)
                {
                    return Json(new { Message = ModelState["DefaultReorderQuantity"].Errors[0].ErrorMessage, Status = "Fa" }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    return Json(new { Message = ResMessage.InvalidModel, Status = "Fa" }, JsonRequestBehavior.AllowGet);
                }
            }

AND YOU ARE DONE.... USE THIS AS PER YOUR REQUIREMENT ... HERE FIELD DEFAULT REORDER QUANTITY IS AN EXAMPLE ...