Reputation: 109
I am validating a form with jquery validate and wanted to display error message only to the email field. I tried something like this
messages: {
txtFirstName: '',
txtDob: '',
txtPhone: '',
txtEmail: "Por favor ingrese una dirección de correo válida. Ej: [email protected]",
Privacyid: ''
}
The error messages get displayed at the top, but p tag is getting created for each of the element. I just need to display error message for email alone.
showErrors: function (errorMap, errorList) {
var msg = "<p>Your form contains " + this.numberOfInvalids() + " errors, see details below.</p>"
$.each(errorMap, function(key, value) {
msg += "<p>" + value + "</p>";
});
$("#errormessages").html(msg);
this.defaultShowErrors(); // default labels from errorPlacement
if (this.numberOfInvalids() > 0) {
$("#errormessages").show();
} else {
$("#errormessages").hide();
}
}
Upvotes: 0
Views: 2085
Reputation: 8351
Just remove showErrors
property and let the plugin create your error elements, you can use errorElement
property to specify the error tag:
$(document).ready(function() {
$("#form").validate({
errorElement: 'p',
errorClass: 'error',
rules: {
email: {
required: true,
email: true
}
},
messages: {
email: "Por favor ingrese una dirección de correo válida. Ej: [email protected]"
}
});
});
.error {
color: #ff0000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.js"></script>
<form id="form">
<fieldset>
<legend>validate only email field</legend>
<p>
<label for="firstname">Firstname</label>
<input id="firstname" name="firstname" type="text">
</p>
<p>
<label for="email">Email (required)</label>
<input id="email" type="email" name="email">
</p>
<p>
<input class="submit" type="submit" value="Submit">
</p>
</fieldset>
</form>
Upvotes: 1