I have implemented this jquery code in my site's sandbox and it functions almost perfectly on an input box in a form. It formats the phone number as it is typed. The issue is the string is restricted to 14 characters, and if a visitor enters a 0 or 1 as the first character the phone number is sent via email and is invalid. How can I restrict a user from entering a 0 or a 1 as the first character?
All my business will be local so there is no need for international telephone formatting. Only North American formatting is required. Before I go live with this I would appreciate any input that will help solve my issue.
Thank you,
$(document).ready(function(){
/***phone number format***/
$(".phone-format").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
return false;
}
var curchr = this.value.length;
var curval = $(this).val();
if (curchr == 3 && curval.indexOf("(") <= -1) {
$(this).val("(" + curval + ")" + "-");
} else if (curchr == 4 && curval.indexOf("(") > -1) {
$(this).val(curval + ")-");
} else if (curchr == 5 && curval.indexOf(")") > -1) {
$(this).val(curval + "-");
} else if (curchr == 9) {
$(this).val(curval + "-");
$(this).attr('maxlength', '14');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
<input id="phone" name="phone" type="text" placeholder="Your Phone (Numbers Only)" class="phone-format" required>
</div>