I have 4 fields where the user should enter values in at least one of them. So I am trying to validate that each of these 4 fields will be required just when all of them are empty otherwise it won't be required.
The rule seems to be working for the one field I picked to try first, but the required error remains even after I provide a value.
This is my code:
$("#ProspectDtlFrm").validate({ rules: { prsptEmail: { required: function(element) { return ( $("#prsptHomePhone").val() == '' && $("#prsptBusinessPhone").val() == '' && $("#prsptMobilePhone").val() =='' ) } } }, messages: { prsptEmail: "Please enter your first name" } });
The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form. You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.
The plugin adds a validationPlugin function to jQuery. fn , so simply check whether it exists or not; if (typeof jQuery. fn.
We're going to use the jQuery Validation Plugin to validate our form. The basic principle of this plugin is to specify validation rules and error messages for HTML elements in JavaScript.
You could use depends
:
$('#ProspectDtlFrm').validate({ rules: { prsptEmail: { required: { depends: function(element) { return ($('#prsptHomePhone').val() == '' && $('#prsptBusinessPhone').val() == '' && $('#prsptMobilePhone').val() == ''); } } } }, messages: { prsptEmail: 'Please enter your 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