views:

29

answers:

1

I've got a form with two sections. Each section expands by its own radio button, so there's only one visible section at a time. And I use ASP.NET MVC HtmlHelper to generate fields like so:

<label for="type-permanent" class="radio active">
    <input type="radio" name="Type" value="Type1" id="type1" /> Label1
</label>
<%= Html.TextBox("Field1", Model.IntProperty1) %>
<label for="type-permanent" class="radio active">
    <input type="radio" name="Type" value="Type2" id="type2" /> Label2
</label>
<%= Html.TextBox("Field2", Model.IntProperty2) %>

I also have two functions so that I could determine, which section is active:

function isType1() { return $("#type1").attr("checked"); }
function isType2() { return $("#type2").attr("checked"); }

Finally, I've got the followind validation methods set up:

Field1: {
    required: isType1,
    min: 1
},
Field2: {
    required: isType2,
    min: 1
}

Now, the point is that if I pass empty model to the view, both fields are set to 0 (default for int). Now if the user fills some fields and tries to submit the form, there is validation error, because even though the field in other section is not required, but it has the value - 0, which is not correct since it must be more that 1. How can I overcome this except clearing fields in hidden sections before form submission?

UPDATE. I guess I need some kind of conditional validation method.

+1  A: 

Hey,

If you can build it in, the required method takes a callback, so maybe you can build in the zero null check into the required validator via: http://docs.jquery.com/Plugins/Validation/Methods/required#dependency-callback

HTH.

Brian
So do you mean I should do something like this:required: function() { return $("#type1").attr("checked") }I guess this is wrong, because it means that the field is required only if it is in visible section AND is more or equal to 1
HiveHicks
Well, if you are allowing zero in some instances and not in others, you need a designator of some sort to identify this case, and then check this case in the required function. So, the ways to do that are, inject "if (<%= (check for model emptiness) %>) return true;". If the model is empty, it gives the field a pass. Or, use the $.data method to attach additional information to the element when the model is empty that says give this element a pass too... But you have to have a designation to do the differentation. Otherwise, there is no way to resolve the difference.
Brian