Add custom validation condition to Data annotation - International Days

International Days

Internationally important Days

Breaking

Home Top Ad

Post Top Ad

Friday, 31 July 2015

Add custom validation condition to Data annotation


I have faced some problem like that in immediate past, That is I am using MVC Data annotation for validation , which is very easy to implement and very easy to change and very minimal code needed for implementing the Data annotation validation .
But i have faced a problem that , In a form validation should be triggered according to a radio button, So I was not able to do using the existing data annotation . I searched for the solution in web and i will explain what i have done .

Create custom attribute class , In this calss we could define the required condition
and we have to inherit the validationAttribute class. Which will allow us to have all the property of default data annotation validate. Then next is to override Isvalid method in this method we are going to write our custome validation .

Also we have to inherit IClientValidatable class . While inheriting this may occur some 'object reference error' so we have to add reference to the System.web.mvc namespace . And also we have to add a method which will return the client validation rules. Here i userd GetClientValidationRules Which return IEnumerable<System.Web.Mvc.ModelClientValidationRule> list and also we have to add our new validation rules in Jquery validate
Note: ModelClientValidationRule may return error refrene error so add reference to the
System.web.webpages dll

The Defnition of new RequiredIf Class

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]

public class RequiredIfAttribute : ValidationAttribute, System.Web.Mvc.IClientValidatable
{
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
_dependentProperty = dependentProperty;
_targetValue = targetValue;
_innerAttribute = new RequiredAttribute();
}
private string _dependentProperty { get; set; }
private object _targetValue { get; set; }
private readonly RequiredAttribute _innerAttribute;


protected override ValidationResult IsValid(object value, ValidationContext context)
{
var dependentValue = context.ObjectInstance.GetType().GetProperty(_dependentProperty).GetValue(context.ObjectInstance, null);

if (dependentValue.ToString() == _targetValue.ToString())
{
if (!_innerAttribute.IsValid(value))
{
return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
}
}
return ValidationResult.Success;
}


public IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(System.Web.Mvc.ModelMetadata metadata, System.Web.Mvc.ControllerContext context)
{
var rule = new System.Web.Mvc.ModelClientValidationRule
{
ErrorMessage = ErrorMessageString,
ValidationType = "requiredif",
};
rule.ValidationParameters["dependentproperty"] = (context as System.Web.Mvc.ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(_dependentProperty);
rule.ValidationParameters["desiredvalue"] = _targetValue is bool ? _targetValue.ToString().ToLower() : _targetValue;

yield return rule;
}

}


The Viewmodel is as below

public class Employee
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public string FullName { get; set; }
[RequiredIf("Check", true)]
public string DateOfBirth { get; set; }
[Required]
public string EducationList { get; set; }
[Required]
public string Gender { get; set; }
[Required]
public string DepartmentId { get; set; }
public bool Check { get; set; }
}

The under lined properties are used to called RequiredIf

The Javascript needed for add validation to the page is as given below

Script

$.validator.unobtrusive.adapters.add('requiredif', ['dependentproperty', 'desiredvalue'], function (options) {
options.rules['requiredif'] = options.params;
options.messages['requiredif'] = options.message;
});

$.validator.addMethod('requiredif', function (value, element, parameters) {
var desiredvalue = parameters.desiredvalue;
desiredvalue = (desiredvalue == null ? '' : desiredvalue).toString();
var controlType = $("input[id$='" + parameters.dependentproperty + "']").attr("type");
var actualvalue = {}
if (controlType == "checkbox" || controlType == "radio") {
var control = $("input[id$='" + parameters.dependentproperty + "']:checked");
actualvalue = control.val();
} else {
actualvalue = $("#" + parameters.dependentproperty).val();
}
if ($.trim(desiredvalue).toLowerCase() === $.trim(actualvalue).toLocaleLowerCase()) {
var isValid = $.validator.methods.required.call(this, value, element, parameters);
return isValid;
}
return true;
});




Your comments help me to improve my knowledge and if any other methods for add custom validation so please leave your valuable comments

2 comments:

Post Bottom Ad

Pages