I have a radio button with values, "Yes" and "No". If user selects "No", the text box fire the required message. So it has to be validated. If user clicks "Yes", the textbox there is no need for validation.
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
{
private RequiredAttribute _innerAttribute = new RequiredAttribute();
public string DependentProperty { get; set; }
public object TargetValue { get; set; }
public RequiredIfAttribute(string dependentProperty, object targetValue)
{
this.DependentProperty = dependentProperty;
this.TargetValue = targetValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// get a reference to the property this validation depends upon
var containerType = validationContext.ObjectInstance.GetType();
var field = containerType.GetProperty(this.DependentProperty);
if (field != null)
{
// get the value of the dependent property
var dependentvalue = field.GetValue(validationContext.ObjectInstance, null);
// compare the value against the target value
if ((dependentvalue == null && this.TargetValue == null) ||
(dependentvalue != null && dependentvalue.Equals(this.TargetValue)))
{
// match => means we should try validating this field
if (!_innerAttribute.IsValid(value))
// validation failed - return an error
return new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName });
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "requiredif",
};
string depProp = BuildDependentPropertyId(metadata, context as ViewContext);
// find the value on the control we depend on;
// if it's a bool, format it javascript style
// (the default is True or False!)
string targetValue = (this.TargetValue ?? "").ToString();
if (this.TargetValue.GetType() == typeof(bool))
targetValue = targetValue.ToLower();
rule.ValidationParameters.Add("dependentproperty", depProp);
rule.ValidationParameters.Add("targetvalue", targetValue);
yield return rule;
}
private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext)
{
// build the ID of the property
string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(this.DependentProperty);
// unfortunately this will have the name of the current field appended to the beginning,
// because the TemplateInfo's context has had this fieldname appended to it. Instead, we
// want to get the context as though it was one level higher (i.e. outside the current property,
// which is the containing object (our Person), and hence the same level as the dependent property.
var thisField = metadata.PropertyName + "_";
if (depProp.StartsWith(thisField))
// strip it off again
depProp = depProp.Substring(thisField.Length);
return depProp;
}
}
purushotham2...
Member
150 Points
315 Posts
How to validate a text box based on radio button selection in ASP.NET MVC 3 and JQuery?
Apr 17, 2012 06:06 AM|LINK
I have a radio button with values, "Yes" and "No". If user selects "No", the text box fire the required message. So it has to be validated. If user clicks "Yes", the textbox there is no need for validation.
CodeHobo
All-Star
18647 Points
2647 Posts
Re: How to validate a text box based on radio button selection in ASP.NET MVC 3 and JQuery?
Apr 17, 2012 06:13 AM|LINK
Can you elaborate more on your design? What is the point of the "No" radio button if a user can't select it? Instead make it a required checkbox.
Blog | Twitter : @Hattan
mudassarkhan
All-Star
78956 Points
13402 Posts
MVP
Re: How to validate a text box based on radio button selection in ASP.NET MVC 3 and JQuery?
Apr 17, 2012 06:53 AM|LINK
Refer
http://www.aspforums.net/Threads/992759/Enable-Disable-Required-Field-Validators-based-on-RadioButton-Selection/
Contact me
Young Yang -...
All-Star
21343 Points
1818 Posts
Microsoft
Re: How to validate a text box based on radio button selection in ASP.NET MVC 3 and JQuery?
Apr 19, 2012 06:11 AM|LINK
Hi
You can create a RequiredIfAttribute, like this:
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable { private RequiredAttribute _innerAttribute = new RequiredAttribute(); public string DependentProperty { get; set; } public object TargetValue { get; set; } public RequiredIfAttribute(string dependentProperty, object targetValue) { this.DependentProperty = dependentProperty; this.TargetValue = targetValue; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { // get a reference to the property this validation depends upon var containerType = validationContext.ObjectInstance.GetType(); var field = containerType.GetProperty(this.DependentProperty); if (field != null) { // get the value of the dependent property var dependentvalue = field.GetValue(validationContext.ObjectInstance, null); // compare the value against the target value if ((dependentvalue == null && this.TargetValue == null) || (dependentvalue != null && dependentvalue.Equals(this.TargetValue))) { // match => means we should try validating this field if (!_innerAttribute.IsValid(value)) // validation failed - return an error return new ValidationResult(this.ErrorMessage, new[] { validationContext.MemberName }); } } return ValidationResult.Success; } public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule() { ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()), ValidationType = "requiredif", }; string depProp = BuildDependentPropertyId(metadata, context as ViewContext); // find the value on the control we depend on; // if it's a bool, format it javascript style // (the default is True or False!) string targetValue = (this.TargetValue ?? "").ToString(); if (this.TargetValue.GetType() == typeof(bool)) targetValue = targetValue.ToLower(); rule.ValidationParameters.Add("dependentproperty", depProp); rule.ValidationParameters.Add("targetvalue", targetValue); yield return rule; } private string BuildDependentPropertyId(ModelMetadata metadata, ViewContext viewContext) { // build the ID of the property string depProp = viewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(this.DependentProperty); // unfortunately this will have the name of the current field appended to the beginning, // because the TemplateInfo's context has had this fieldname appended to it. Instead, we // want to get the context as though it was one level higher (i.e. outside the current property, // which is the containing object (our Person), and hence the same level as the dependent property. var thisField = metadata.PropertyName + "_"; if (depProp.StartsWith(thisField)) // strip it off again depProp = depProp.Substring(thisField.Length); return depProp; } }More details: http://blogs.msdn.com/b/simonince/archive/2011/02/04/conditional-validation-in-asp-net-mvc-3.aspx
Hope this helpful
Regards
Young Yang
Feedback to us
Develop and promote your apps in Windows Store