I am using jQuery Validation Plugin to validate a phone number from an optional input field.
Here is my form:
<form id="input-form" action="" method="post">
<p>
<label for="name">Name <span>(required, at least 3 characters)</span></label>
<input id="name" name="name">
</p>
<p>
<label for="email">E-Mail <span>(required)</span></label>
<input id="email" name="email">
</p>
<p>
<label for="phone">Phone <span>(optional, US phone number only)</span></label>
<input id="phone" name="phone">
</p>
<p>
<input type="submit" value="SUBMIT">
</p>
</form>
Here is what I have tried to set the rules to validate the input field for phone number
$(document).ready(function() {
$("#input-form").validate({
rules: {
name : {
required: true,
minlength: 3
},
email: {
required: true,
email: true
},
phone: {
required: {
depends: function(elem) {
return $("#phone").val().length == 11
}
}
}
},
messages : {
name: {
minlength: "Name should be at least 3 characters"
},
email: {
email: "The email should be in the format: [email protected]"
},
phone: {
required: "Please enter a valid US phone number"
}
}
});
});
It's still not working. Can anyone please help me out?
CodePudding user response:
In the additional-methods.js file are several phone number validation methods you can use phoneUS should satisfy your pattern
rules: {
phoneNumber: {
phoneUS: true
}
}
CodePudding user response:
I was able to validate the input field for phone number. Here is my solution:
rules: {
phone: {
required: {
depends: function(elem) {
return $("#phone").val().length > 9
}
},
number: true,
rangelength: [10, 10]
}
},
messages: {
phone: {
required: "Please enter a valid US phone number",
number: "Please enter only numbers for phone number",
rangelength: "Please enter a valid US phone number"
}
}