简体   繁体   中英

Javascript regular expression for phone number validation.(String contains only at least 1 digit, 0 or more spaces and '-'

Currently I have an expression:

numMatches = phone.match(/[^\d\s\-]/gi);

if (numMatches != null) {
    alert(invPhnNo);
}   

This gives an alert if any characters other than digit, space and hyphen are entered. But still accepts if only hyphen and spaces are given without a single digit. Now i would want it to alert if atleast a digit is not there. So a digit is mandatory. Can have zero or more spaces and hyphen and no other characters.

Can anyone suggest an approach to this?

You could either use the standard regexp refered to by Trever, but you could also simply run another .match(/\d+/g) on the string and if both succeed, you can be sure that it complies with your requirements and also has at least one digit.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM