Reputation: 6129
I had a phone number validation script running across multiple sites that suddenly broke. Functioning properly, it requires exactly 10 characters, strips ALL non-numerical characters (including x,#,*,(,-
), validates phone numbers using area codes (only 5 in snippet below for the sake of space). However, currently, the phone fields are allowing all characters and any quantity of characters. Just trying to find out what might be wrong here.
Validation Script
jQuery.validator.addMethod("phone", function(value, element) {
if(value.length > 10)
{
if(value.charAt(0) == 1) {
value = value.substr(1)
}
var value = value.replace(/\D/ig,'');
$(element).val(value)
}
var list = [201,202,203,204,205];
var area = value.substring(0, 3);
if(list.indexOf(parseInt(area)) == -1)
{
return false;
}
return value.length == 10
}, "Invalid Phone");
jQuery('#form form').validate({
rules: {
Email: {
required: true,
email: true
},
First_Name: {
required: true,
alpha: true
},
Last_Name: {
required: true,
alpha: true
},
Primary_Phone: {
phone: true
},
City: {
alpha: true
}
},
messages: {
required: "Required"
}
});
Phone field
<input name="Primary_Phone" type="tel" class="phone form-control" placeholder="5555555555" required="">
Upvotes: 0
Views: 94
Reputation: 5129
For you script given, if user input greater than 10 characters, all non-numerical characters are striped out. I think you want to stripe out all non-numerical characters regardless of how many characters users input?
jQuery.validator.addMethod("phone", function(value, element) {
var value = value.replace(/\D/ig,'');
$(element).val(value)
if(value.length > 10)
{
if(value.charAt(0) == 1) {
value = value.substr(1)
}
}
var list = [201,202,203,204,205];
var area = value.substring(0, 3);
if(list.indexOf(parseInt(area)) == -1)
{
return false;
}
console.log(value);
return value.length == 10
}, "Invalid Phone");
jQuery('form').validate({
rules: {
Primary_Phone: {
phone: true
},
},
messages: {
required: "Required"
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<form>
<input name="Primary_Phone" type="tel" class="phone form-control" placeholder="5555555555" required="">
</form>
Upvotes: 1