I'm developing a web application using ASP .NET MVC 1.0 and jQuery (including the validation plugin). The server-side markup for a typical "edit entity" view is as follows
<label for="FirstName">FirstName:</label>
<%= Html.TextBox("FirstName", Model.FirstName) %>
<%= Html.ValidationMessage("FirstName") %>
When invalid data is posted to the FirstName field, the resulting HTML is
<label for="FirstName">FirstName:</label>
<input type="text" value="" name="FirstName" id="FirstName" class="input-validation-error text">
<span class="field-validation-error">Please enter the first name.</span>
Which is exactly what you would expect from ASP .NET MVC out of the box.
I am now adding client-side validation with jQuery, and would like it to behave in exactly the same way - i.e. the input control is given a class of input-validation-error and a span is added with a class of field-validation-error, for showing the error message.
I'm almost there, but not quite. Using the errorElement option gets the validator to create a span for the error message, rather than a label. Using the errorClass option means that the input element is given a class of input-validation-error.
The problem I've got is that the error message span also gets a class of input-validation-error, and I want it to have field-validation-error.
I've tried using the highlight and unhighlight functions to correct this, but as soon as I start messing with the classes on the span, the validation itself stops working and just posts the form to the server.
Anyone out there got any ideas as to how I can fix this? Thanks.
The above properties are set True by default which means MVC 5 platform ensures that client side validation on form validation is on. For jQuery form validation to work, we set "HtmlHelper. UnobtrusiveJavaScriptEnabled = false;" property false in the register form instead of "web.
The jQuery validation plugin leverages a CSS selector like syntax to apply a set of validation rules. You can download the plugin (js) file from jQuery website. The password and confirm password objects are matched by the validation plugin for you and shows the message on the equalTo attribute if they don't match.
Checkout the errorPlacement callback:
$('form').validate({
errorClass: 'input-validation-error',
errorElement: 'span',
errorPlacement: function(error, element) {
// Insert and manipulate the span element here:
error.insertAfter(element)
.removeClass('input-validation-error')
.addClass('field-validation-error');
},
rules: {
FirstName: {
required: true
}
},
messages: {
FirstName: {
required: 'Please enter the first name.'
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With