Hi,
I’ve got a form with some jQuery validation that, for the most part, is working fine.
However, the one part that I’m struggling with is making a text input field required, if a checkbox is checked.
The form asks for CRB/DBS information. The checkbox is ‘Do you have a CRB/DBS?’. If this is checked, then the fields for CRBNumber and Date etc should then be required.
Here’s my code:
<script language="javascript">
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "<span class='testing'> Please enter only letters</span>");
$(function() {
$( "#NewVisitorForm" ).validate({
rules: {
FirstName: {
required: true,
lettersonly: true
},
Surname: {
required: true,
lettersonly: true
},
CRBNum: {
digits: true,
required: $('#hasCRB').is(':checked')
}
},
messages: {
FirstName: {
required: "<span class='testing'> Please enter your first name</span>"
},
Surname: {
required: "<span class='testing'> Please enter your surname</span>"
},
CRBNum: {
required: "<span class='testing'> A CRB/DBS Number is required if you tick the CRB box.</span>",
digits: "<span class='testing'> Please enter only numbers here.</span>"
},
}
});
});
</script>
And here’s the form:
<form method="post" action="[script name]" id="NewVisitorForm" name="NewVisitorForm">
First Name: <input type="text" name="FirstName" id="FirstName">
Surname: <input type="text" name="Surname" id="Surname">
Does this person have a CRB/DBS?:<input type="checkbox" name="hasCRB" id="hasCRB">
CRB/DBS Number: <input type="text" name="CRBNum" id="CRBNum">
CRB/DBS Issue Date: <input type="text" name="CRBDate" id="CRBDate" readonly><p>
<input type="submit" name="submit" id="buttonSave" value="SAVE">
<input type="reset" name="reset" id="buttonReset" value="RESET">
</form>
The FirstName / Surname validation rules are working perfectly.
And I know that $('#hasCRB').is(':checked')
returns true or false correctly… but the validation rule doesn’t seem to be applied correctly.
Any help would be gratefully received.