Validate phone number in javascript using regular expression with same functionality like keypress
$('#phone').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
Here's a quick, working example. JS Fiddle
<style>
.invalid {
border: 2px solid red;
}
</style>
<input id="input" type="text" />
<script>
// save reference to input
const input = $('#input');
// save regex to check against
const regex = new RegExp('^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$', 'im');
// on keypress, get user input
// strip non-digits (1-2 => 12 | 5.6 => 56)
// run regex test and add/remove class to show validation
function checkPhoneNumber(){
const user_input = input.val().replace(/\D/g, ""); // replace any non-digits with nothing
const valid_phone = regex.test(user_input);
if (valid_phone){
input.removeClass('invalid');
} else {
input.addClass('invalid');
}
}
// attach listener with function
input.on('keyup', checkPhoneNumber);
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.