RequiredIf fails on client side with radio buttons.

Jan 4, 2011 at 3:39 PM

Hi I have the following. 

 

//Model
public String rdoAppTypeOptions { get; set; }


[RequiredIf("rdoAppTypeOptions", "This is One", ErrorMessage = "Please select one option")]
public string rdoSelfFundingOptions { get; set; }


//View
<td> 
Yes&#160;<%: Html.RadioButtonFor(model => model.rdoSelfFundingOptions, "Yes") %>&#160;&#160; 
 No&#160;<%: Html.RadioButtonFor(model => model.rdoSelfFundingOptions, "No") %>
<%: Html.ValidationMessageFor(model => model.rdoSelfFundingOptions) %>
</td>

When "This is One" option is selected on the radio button rdoAppTypeOptions, the value of the rdoSelfFundingOption is always yes, whether if it is selected or not, and then the validation on the client side fails, but it comes back from the server, therefore the validation is applied but not on the client side.

Does anyone had this issue before? if so, How did you fixed?

Thanks in advance.

Cesar.

 

Aug 19, 2011 at 8:37 PM
Edited Aug 19, 2011 at 8:40 PM

I just encountered this problem and I have a solution.

Replace - They can be found around lines (91,110,125)

 

if (value != null && value.toString().replace(/^\s\s*/, '').replace(/\s\s*$/, '') != "")
//                return true;

 

With

 

 
//'this' is the jquery validator
return jQuery.validator.methods.required.call(this, value, element) == true;

 

 

After debugging and studying the validation method of the jQuery Validation plugin, I found out that the foolproof validation logic, to see of a field is empty, does not take into account the fact that a radio button(checkbox too?) always returns it's value even if its not selected. Instead call the required method included in the jQuery Validation plug in. That method takes into account the discrepancies between different elements. I have yet to encounter a problem by replacing the aforementioned code but I will keep testing and submit an issue to the developer.

Jun 18, 2012 at 1:33 PM

@jcruz2us please tell me where and in which file to make the changes exactly.

Thanks

Jun 18, 2012 at 9:42 PM

If your using the latest release

then in mvcfoolproof.unobtrusive.js only replace lines 116, 130, and 142

 

replace the following if statement

 

if (value != null && value.toString().replace(/^\s\s*/, '').replace(/\s\s*$/, '') != "") return true;

with

 

return jQuery.validator.methods.required.call(this, value, element) == true;

 

 

I submitted this a while ago and it worked flawlessly but you should really test it out.

Aug 8, 2012 at 2:34 AM

Actually, I think there's a problem, after implementing the fix above, the error message is the default one "The {0} field is required" and doesn't accept the custom one specified in the attribute.

Am I missing something?

Vincent