자바 스크립트로 전화 번호 확인
일부 웹 사이트 에서이 코드를 찾았으며 완벽하게 작동합니다. 전화 번호가
(123) 456-7890 또는 123-456-7890 형식 중 하나인지 확인합니다.
문제는 내 클라이언트 (어쩌면 클라이언트 물건 일지 모르겠다)가 10 개의 숫자를 연속적으로 다른 형식을 추가하려고한다는 것입니다 : 1234567890 .
이 정규식을 사용하고 있습니다.
/^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/
다른 형식의 유효성 검사를 추가하려면 어떻게해야합니까? 정규식이 좋지 않습니다.
먼저, 형식 검사기는 NANP (국가 코드 +1) 숫자 에만 적합 합니다. 북미 이외의 지역에서 전화 번호를 가진 사람이 애플리케이션을 사용합니까? 그렇다면 그러한 사람들이 완벽하게 유효한 [국제] 번호를 입력하지 못하게하고 싶지 않습니다.
둘째, 유효성 검사가 잘못되었습니다. NANP 번호의 형식은 취 숫자 2-9이며, 숫자 0-9입니다. 또한 지역 번호가 아닌 지역 번호 (800, 888, 877, 866, 855, 900)의 번호로 교환 할 수있는 경우를 제외하고 는 지역 서비스 및 교환은 특정 서비스와 혼동을 피하기 위해 두 가지 형식으로 끝나지 않을 수 있습니다 .NXX NXX XXXX
N
X
N11
N11
따라서 정규 전화 번호는 유효한 전화 번호가 아니지만 번호 (123) 123 4566을 전달합니다. 로 교체 \d{3}
하여 문제를 해결할 수 있습니다 [2-9]{1}\d{2}
.
마지막으로 웹 브라우저에서 사용자 입력을 확인하고 있다는 느낌이 들었습니다. 클라이언트 측 유효성 검사는 사용자에게 제공 하는 편의 일뿐입니다 . 여전히 서버의 모든 입력을 다시 검증해야합니다.
TL; DR 은 정규 표현식을 사용하여 전화 번호 나 URL 과 같은 복잡한 실제 데이터의 유효성 을 검사 하지 않습니다 . 전문 라이브러리를 사용하십시오 .
내가 선택한 정규식은 다음과 같습니다.
/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im
유효한 형식 :
(123) 456-7890
(123)456-7890
123-456-7890
123.456.7890
1234567890
+31636363634
075-63546725
10 자리에서 10 자리 만 찾으려면 숫자를 제외한 모든 것을 무시하십시오.
return value.match(/\d/g).length===10;
다음 REGEX는 이러한 형식 중 하나를 확인합니다.
(123) 456-7890
123-456-7890
123.456.7890
1234567890
/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s\.]{0,1}[0-9]{3}[-\s\.]{0,1}[0-9]{4}$/
내가 할 일은 형식을 무시하고 숫자 내용을 확인하는 것입니다.
var originalPhoneNumber = "415-555-1212";
function isValid(p) {
var phoneRe = /^[2-9]\d{2}[2-9]\d{2}\d{4}$/;
var digits = p.replace(/\D/g, "");
return phoneRe.test(digits);
}
/^[+]*[(]{0,1}[0-9]{1,3}[)]{0,1}[-\s\./0-9]*$/g
(123) 456-7890
+ (123) 456-7890
+ (123) -456-7890
+ (123)-456-7890
+ (123)-456-78-90
123-456-7890
123.456.7890
1234567890
+31636363634
075-63546725
이것은 매우 느슨한 옵션 이며이 방법을 선호합니다. 주로 사용자가 전화 번호를 추가 해야하는 등록 양식으로 사용합니다. 일반적으로 사용자는 엄격한 서식 규칙을 적용하는 양식에 문제가 있으므로 숫자와 형식을 표시하거나 데이터베이스에 저장하기 전에 사용자가 선호합니다. http://regexr.com/3c53v
더 명확한 것을 사용하는 것이 좋습니다 (특히 누가 코드를 유지해야 할지를 생각하십시오) ... 어떻게 :
var formats = "(999)999-9999|999-999-9999|9999999999";
var r = RegExp("^(" +
formats
.replace(/([\(\)])/g, "\\$1")
.replace(/9/g,"\\d") +
")$");
정규 표현식이 명확한 템플릿으로 작성된 곳은 어디입니까? 새로운 것을 추가하는 것은 쉬운 일이 아니며 고객 자신도 "옵션"페이지에서 그렇게 할 수 있습니다.
str이 다음 중 하나가 될 수있는 곳 : 555-555-5555 (555)555-5555 (555) 555-5555555555 5555 5555555555 1 555555 5555
function telephoneCheck(str) {
var isphone = /^(1\s|1|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/.test(str);
alert(isphone);
}
telephoneCheck("1 555 555 5555");
이것은 작동합니다 :
/^(()?\d{3}())?(-|\s)?\d{3}(-|\s)?\d{4}$/
?
앞의 그룹은 0 또는 1 번 일치해야 문자 의미한다. 그룹 (-|\s)
은 a -
또는 |
문자 와 일치합니다 . ?
정규식에서이 그룹의 두 번째 항목 이후에 추가하면 연속 된 10 자리의 시퀀스를 일치시킬 수 있습니다.
이것을 시도하십시오-국제 형식에 대한 유효성 검사도 포함됩니다.
/^[+]?(1\-|1\s|1|\d{3}\-|\d{3}\s|)?((\(\d{3}\))|\d{3})(\-|\s)?(\d{3})(\-|\s)?(\d{4})$/g
이 정규식은 다음 형식을 확인합니다.
- (541) 754-3010 국내
- + 1-541-754-3010 국제
- 1-541-754-3010 미국에서 전화 걸기
- 001-541-754-3010 독일에서 전화 걸기
- 191 541 754 3010 프랑스에서 전화 걸기
/^\+?1?\s*?\(?\d{3}(?:\)|[-|\s])?\s*?\d{3}[-|\s]?\d{4}$/
이 게시물은 오래되었지만 내 기고를 남기고 싶습니다. 5555555555 555-555-5555 (555)555-5555 1 (555) 555-5555 1 555 555 5555 1 555-555-5555 1 (555) 555-5555
이들은 허용되지 않습니다 :
555-5555->이 사용을 수락하려면 : ^\+?1?\s*?\(?(\d{3})?(?:\)|[-|\s])?\s*?\d{3}[-|\s]?\d{4}$
5555555->이 사용을 수락하려면 : ^\+?1?\s*?\(?(\d{3})?(?:\)|[-|\s])?\s*?\d{3}[-|\s]?\d{4}$
1 555) 555-5555123 ** & !! asdf # 55555555 (6505552368) 2 (757) 622-7382 0 (757) 622-7382 -1 (757) 622-7382 2757757622-7382 10 (757) 622 -7382 27576227382 (275) 76227382 2 (757) 6227382 2 (757) 622-7382 (555) 5 (55?)-5555
이것은 내가 사용한 코드입니다.
function telephoneCheck(str) {
var patt = new RegExp(/^\+?1?\s*?\(?\d{3}(?:\)|[-|\s])?\s*?\d{3}[-|\s]?\d{4}$/);
return patt.test(str);
}
telephoneCheck("+1 555-555-5555");
모든 사람의 답변은 훌륭하지만 여기에 조금 더 포괄적이라고 생각되는 답변이 있습니다 ...
이것은 한 줄에 단일 숫자를 사용하는 자바 스크립트 일치를 위해 작성되었습니다.
^(?!.*911.*\d{4})((\+?1[\/ ]?)?(?![\(\. -]?555.*)\( ?[2-9][0-9]{2} ?\) ?|(\+?1[\.\/ -])?[2-9][0-9]{2}[\.\/ -]?)(?!555.?01..)([2-9][0-9]{2})[\.\/ -]?([0-9]{4})$
단어 경계에서 일치 시키려면 ^와 $를 \ b로 변경하십시오.
이 솔루션에 대한 제안, 수정 또는 비판을 환영합니다. 내가 알 수있는 한, 이것은 NANP 형식과 일치합니다 (미국 번호의 경우-이를 만들 때 다른 북미 국가를 확인하지 않았습니다) .911 오류 (지역 코드 또는 지역 코드에있을 수 없음)를 피하고 제거합니다. 실제로 유효하지 않은 555 숫자 만 (지역 코드는 555이고 01xx는 x = 임의의 숫자).
정말 간단
"9001234567".match(/^\d{10}$/g)
/^(()?\d{3}())?(-|\s)?\d{3}(-|\s)?\d{4}$/
?
앞의 그룹은 0 또는 1 번 일치해야 문자 의미한다. 그룹 (-|\s)
은 a -
또는 |
문자 와 일치합니다 .
전화 번호 확인은 어려운 작업이라는 데 동의해야합니다. 이 특정 문제에 관해서는 정규식을
/^(()?\d{3}())?(-|\s)?\d{3}(-|\s)\d{4}$/
에
/^(()?\d{3}())?(-|\s)?\d{3}(-|\s)?\d{4}$/
불필요하게되는 유일한 요소는 마지막 대시 / 공간뿐입니다.
이 코드보다 입력 태그를 사용하면 도움이 될 것입니다. 나는이 코드를 직접 작성하고 이것이 입력에 사용하기에 매우 좋은 방법이라고 생각합니다. 그러나 형식을 사용하여 변경할 수 있습니다. 사용자가 입력 태그에서 형식을 수정하는 데 도움이됩니다.
$("#phone").on('input', function() { //this is use for every time input change.
var inputValue = getInputValue(); //get value from input and make it usefull number
var length = inputValue.length; //get lenth of input
if (inputValue < 1000)
{
inputValue = '1('+inputValue;
}else if (inputValue < 1000000)
{
inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, length);
}else if (inputValue < 10000000000)
{
inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, 6) + '-' + inputValue.substring(6, length);
}else
{
inputValue = '1('+ inputValue.substring(0, 3) + ')' + inputValue.substring(3, 6) + '-' + inputValue.substring(6, 10);
}
$("#phone").val(inputValue); //correct value entered to your input.
inputValue = getInputValue();//get value again, becuase it changed, this one using for changing color of input border
if ((inputValue > 2000000000) && (inputValue < 9999999999))
{
$("#phone").css("border","black solid 1px");//if it is valid phone number than border will be black.
}else
{
$("#phone").css("border","red solid 1px");//if it is invalid phone number than border will be red.
}
});
function getInputValue() {
var inputValue = $("#phone").val().replace(/\D/g,''); //remove all non numeric character
if (inputValue.charAt(0) == 1) // if first character is 1 than remove it.
{
var inputValue = inputValue.substring(1, inputValue.length);
}
return inputValue;
}
로컬이 아닌 전화 번호 (800 및 900 유형)를 선택하기위한 솔루션을 추가하고 싶었습니다.
(\+?1[-.(\s]?|\()?(900|8(0|4|5|6|7|8)\3+)[)\s]?[-.\s]?\d{3}[-.\s]?\d{4}
Google은 자바 스크립트 ( https://github.com/googlei18n/libphonenumber) 에서 전화 번호를 처리하기위한 훌륭한 라이브러리를 보유하고 있습니다 . Java 및 C ++에서도 작동합니다.
프로덕션 환경에서 실제로 테스트해야하기 때문에 이것을 사용하는 것이 좋습니다. 따라서 릴레이하기에 매우 안전해야합니다.
이 기능은 우리에게 잘 작동했습니다.
let isPhoneNumber = input => {
try {
let ISD_CODES = [93, 355, 213, 1684, 376, 244, 1264, 672, 1268, 54, 374, 297, 61, 43, 994, 1242, 973, 880, 1246, 375, 32, 501, 229, 1441, 975, 591, 387, 267, 55, 246, 1284, 673, 359, 226, 257, 855, 237, 1, 238, 1345, 236, 235, 56, 86, 61, 61, 57, 269, 682, 506, 385, 53, 599, 357, 420, 243, 45, 253, 1767, 1809, 1829, 1849, 670, 593, 20, 503, 240, 291, 372, 251, 500, 298, 679, 358, 33, 689, 241, 220, 995, 49, 233, 350, 30, 299, 1473, 1671, 502, 441481, 224, 245, 592, 509, 504, 852, 36, 354, 91, 62, 98, 964, 353, 441624, 972, 39, 225, 1876, 81, 441534, 962, 7, 254, 686, 383, 965, 996, 856, 371, 961, 266, 231, 218, 423, 370, 352, 853, 389, 261, 265, 60, 960, 223, 356, 692, 222, 230, 262, 52, 691, 373, 377, 976, 382, 1664, 212, 258, 95, 264, 674, 977, 31, 599, 687, 64, 505, 227, 234, 683, 850, 1670, 47, 968, 92, 680, 970, 507, 675, 595, 51, 63, 64, 48, 351, 1787, 1939, 974, 242, 262, 40, 7, 250, 590, 290, 1869, 1758, 590, 508, 1784, 685, 378, 239, 966, 221, 381, 248, 232, 65, 1721, 421, 386, 677, 252, 27, 82, 211, 34, 94, 249, 597, 47, 268, 46, 41, 963, 886, 992, 255, 66, 228, 690, 676, 1868, 216, 90, 993, 1649, 688, 1340, 256, 380, 971, 44, 1, 598, 998, 678, 379, 58, 84, 681, 212, 967, 260, 263],
//extract numbers from string
thenum = input.match(/[0-9]+/g).join(""),
totalnums = thenum.length,
last10Digits = parseInt(thenum) % 10000000000,
ISDcode = thenum.substring(0, totalnums - 10);
//phone numbers are generally of 8 to 16 digits
if (totalnums >= 8 && totalnums <= 16) {
if (ISDcode) {
if (ISD_CODES.includes(parseInt(ISDcode))) {
return true;
} else {
return false;
}
} else {
return true;
}
}
} catch (e) {}
return false;
}
console.log(isPhoneNumber('91-9773207706'));
\\(?\d{3}\\)?([\-\s\.])?\d{3}\1?\d{4}
변수 형식의 전화 번호를 확인합니다.
\\(?\d{3}\\)?
괄호로 묶은 3 자리 숫자를 찾습니다.
([\-\s\.])?
이 구분 문자 중 하나를 찾습니다.
\d{3}
3 자리를 찾습니다
\1
uses the first matched separator - this ensures that the separators are the same. So (000) 999-5555 will not validate here because there is a space and dash separator, so just remove the "\1" and replace with the separator sub-pattern (doing so will also validate non standard formats). You should however be format hinting for user input anyway.
\d{4}
finds 4 digits
Validates:
- (000) 999 5555
- (000)-999-5555
- (000).999.5555
- (000) 999-5555
- (000)9995555
- 000 999 5555
- 000-999-5555
- 000.999.5555
- 0009995555
BTW this is for JavaScript hence to double escapes.
There are too many regex variants to validate a phone number. I recommend this article: JavaScript: HTML Form - Phone Number validation, where multiple variants are specified for each case. If you want to deepen in regex for a custom expression, you can review this documentation.
This reg ex is suitable for international phone numbers and multiple formats of mobile cell numbers.
Here is the regular expression: /^(+{1}\d{2,3}\s?[(]{1}\d{1,3}[)]{1}\s?\d+|+\d{2,3}\s{1}\d+|\d+){1}[\s|-]?\d+([\s|-]?\d+){1,2}$/
Here is the JavaScript function
function isValidPhone(phoneNumber) {
var found = phoneNumber.search(/^(\+{1}\d{2,3}\s?[(]{1}\d{1,3}[)]{1}\s?\d+|\+\d{2,3}\s{1}\d+|\d+){1}[\s|-]?\d+([\s|-]?\d+){1,2}$/);
if(found > -1) {
return true;
}
else {
return false;
}
}
This validates the following formats:
+44 07988-825 465 (with any combination of hyphens in place of space except that only a space must follow the +44)
+44 (0) 7988-825 465 (with any combination of hyphens in place of spaces except that no hyphen can exist directly before or after the (0) and the space before or after the (0) need not exist)
123 456-789 0123 (with any combination of hyphens in place of the spaces)
123-123 123 (with any combination of hyphens in place of the spaces)
123 123456 (Space can be replaced with a hyphen)
1234567890
No double spaces or double hyphens can exist for all formats.
Validate phone number + return formatted data
function validTel(str){
str = str.replace(/[^0-9]/g, '');
var l = str.length;
if(l<10) return ['error', 'Tel number length < 10'];
var tel = '', num = str.substr(-7),
code = str.substr(-10, 3),
coCode = '';
if(l>10) {
coCode = '+' + str.substr(0, (l-10) );
}
tel = coCode +' ('+ code +') '+ num;
return ['succes', tel];
}
console.log(validTel('+1 [223] 123.45.67'));
Simple Regular expression: /\b\d{3}[-.]?\d{3}[-.]?\d{4}\b/g
Check out the format, hope it works :
444-555-1234
f:246.555.8888
m:1235554567
Try this js function. Returns true if it matches and false if it fails Ref
function ValidatePhoneNumber(phone) {
return /^\+?([0-9]{2})\)?[-. ]?([0-9]{4})[-. ]?([0-9]{4})$/.test(phone);
}
try this
/^[\+]?\d{2,}?[(]?\d{2,}[)]?[-\s\.]?\d{2,}?[-\s\.]?\d{2,}[-\s\.]?\d{0,9}$/im
valid formats:
- (123) 456-7890
- (123)456-7890
- 123-456-7890
- 123.456.7890
- 1234567890
- +31636363634
- +3(123) 123-12-12
- +3(123)123-12-12
- +3(123)1231212
- +3(123) 12312123
- 075-63546725
Validate phone number with an indian standard like start with only 6,7,8 or 9 and total digit must be 10
The solution is tested and working
if(phone=='')
{
alert("please fill out the field");
}
if ($('#phone').val()!="")
{
if(!phoneno.test(phone))
{
alert("enter valid phone number with indian standard.")
exit;
}
else
{
alert("valid phone number");
}
}
참고URL : https://stackoverflow.com/questions/4338267/validate-phone-number-with-javascript
'IT story' 카테고리의 다른 글
포지셔닝 (0) | 2020.07.12 |
---|---|
matplotlib에서 프레임을 제거하는 방법 (pyplot.figure vs matplotlib.figure) (frameon = matplotlib에서 잘못된 문제) (0) | 2020.07.12 |
MySQL 잘못된 날짜 시간 값 : '0000-00-00 00:00:00' (0) | 2020.07.12 |
다른 점을 기준으로 점 회전 (2D) (0) | 2020.07.12 |
MySQL에서 일괄 삽입을 수행하는 방법 (0) | 2020.07.11 |