I am trying to tap into the HTML.ValidationMessage() element to write so really custom client side validation with jQuery. Is this even possible? My server side validation is displayed using the HTML.ValidationMessage(), and I am wondering how I would access that element to display a custom message using jQuery before a form submit.
I know there are a few plugins out there to do some of this stuff, but I would really like complete control with my validation.
Here is a bit of the Javascript code I have currently. Basically it adds the validation ‘class’ to the input element on submit, however not sure how to access the Html.ValidationMessage to output something like ‘Email required.’
<script type='text/javascript'> $(document).ready(function() { $('input[type=submit]').click(function() { var valid = true; // email blank if ($('input[name='email']').val().length < 1) { $('input[name='email']').addClass('input-validation-error'); valid = false; } return valid; }) }); </script>
And Code from the View:
<p> <label for='email'> Email:</label> <%= Html.TextBox('email') %> <%= Html.ValidationMessage('email') %> </p>
You could write a ton of code to do this. Or you could just use xVal, which is free and does exactly this, plus much more. Put value annotations on your .NET types, add a couple of simple things to your aspx, and you get jQuery validation for free. Plus it comes with providers for popular frameworks, and it’s very customizable in case you need more complex validation.
I see no need to reinvent the wheel here.