I'm using a jQuery plugin to build an input mask, but my code is too large.
The user must not be able to start the phone number with zero. The error message has to disappear when he types the right number.
How can I optimize this code? Can I use an array for the numbers? I haven't found a way to do this. Thanks in advance!
var inputMask = function(val) {
return '(00) 0 0000-0000'
},
noZero = {
onKeyPress: function(val, e, field, options) {
if (field.val() == "") {
document.getElementById("PhoneError").innerHTML = "";
} else if (field.val() == "(1") {
document.getElementById("PhoneError").innerHTML = "";
} else if (field.val() == "(2") {
document.getElementById("PhoneError").innerHTML = "";
} else if (field.val() == "(3") {
document.getElementById("PhoneError").innerHTML = "";
} else if (field.val() == "(4") {
document.getElementById("PhoneError").innerHTML = "";
} else if (field.val() == "(5") {
document.getElementById("PhoneError").innerHTML = "";
} else if (field.val() == "(6") {
document.getElementById("PhoneError").innerHTML = "";
} else if (field.val() == "(7") {
document.getElementById("PhoneError").innerHTML = "";
} else if (field.val() == "(8") {
document.getElementById("PhoneError").innerHTML = "";
} else if (field.val() == "(9") {
document.getElementById("PhoneError").innerHTML = "";
} else if (field.val() == "(0") {
document.getElementById("PhoneError").innerHTML = "Don't start with zero";
field.val(field.val().substr(0, 1))
}
field.mask(inputMask.apply({}, arguments), options)
}
};
$("input[type='tel']").mask(inputMask, noZero)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.11/jquery.mask.min.js"></script>
<input type="tel" id="tel" placeholder="tel">
<div id="PhoneError" style="color:red"></div>