Client side validation not working for hidden field in asp.net mvc 3

Suhas picture Suhas · Oct 17, 2011 · Viewed 9.4k times · Source

I have got a hidden field with a validation for it as below

@Html.HiddenFor(m => m.Rating)
@Html.ValidationMessageFor(m => m.Rating)

The Rating property has Range validator attribute applied with range being 1-5. This is put inside a form with a submit button.

I have then got following jquery that sets the value in hidden field on some user event (Basically user clicks on some stars to rate)

$(".star").click(function(){
    $("#Rating").val(2);
});

Now if I submit the form without the user event that sets the hidden field, the validation works. The error messages is displayed properly and it works all client side.

Now, in this situation, if I click on stars, that invokes the above javascript a sets the hidden field, the validation error message would not go away. I can submit the form after the hidden variable has some valid value. But I'm expecting that the client side validation should work. (When the hidden variable has been set with some valid value, the validation error should go away)

Initially I thought, the jquery validation would be invoked on some special events so I tried raising click, change, keyup, blur and focusout events myself as below

$(".star").click(function(){
    $("#Rating").val(2);
    $("#Rating").change();
});

But this is still not working. The error messages once appeared, does not go away at all.

Answer

Reynold Salceda picture Reynold Salceda · Nov 14, 2011

You can wrap your hidden field with a div put somewhere but still inside the <form>. Add css to kick it to outer space.

<div style="position:absolute; top:-9999px; left:-9999px">
<input id="Rating" type="hidden" name="rating" >
</div>

Then add the following label to where you want to show the error:

<label for="rating" class="error" style="display:none">I am an an error message, please modify me.</label>