简体   繁体   English

使用 JavaScript 验证电话号码

[英]Valid a phone number using JavaScript

I'm trying to validate phone number such as 123-456-7891 by using JavaScript and here my code :我正在尝试使用 JavaScript 验证电话号码,例如123-456-7891 ,这里是我的代码:

 <script> function validphnum() { var x = document.getElementById("phnum").value; var format = [0-9]{3}-[0-9]{3}-[0-9]{4}; if (format.test(x)) alert("Valid Phone Number"); else alert("Invalid Phone Number"); } </script>
 <body> <div class="form"> <label for="phnum">Enter Phone Number (XXX-XXX-XXXX): </label> <input type = "text" id = "phnum"> <button onclick="validphnum()" type="button">Submit</button> </div> </body>

A couple of small changes to the format regex variable should fix this.format正则表达式变量进行一些小的更改应该可以解决此问题。

We need to add / before and after the expression to ensure it's recognized as a regular expression.我们需要在表达式之前和之后添加/以确保它被识别为正则表达式。

Also the boundary assertions ^ and $ at either end to ensure the user can't enter characters before or after the phone number.两端的边界断言^$也确保用户不能在电话号码之前或之后输入字符。

 function validphnum() { var x = document.getElementById("phnum").value; var format = /^[0-9]{3}-[0-9]{3}-[0-9]{4}$/; if (format.test(x)) alert("Valid Phone Number"); else alert("Invalid Phone Number"); }
 <body> <div class="form"> <label for="phnum">Enter Phone Number (XXX-XXX-XXXX): </label> <input type = "text" id = "phnum"> <button onclick="validphnum()" type="button">Submit</button> </div> </body>

/^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im

The following example uses the regex in Figure I .以下示例使用图 I中的正则表达式。 In validation when change event is fired on <form> and the input event is fired on <form> as well.在 <form> 上触发更改事件并且在<form> <form>触发输入事件时进行验证。 During submit event, the built-in validation also uses the regex by the <input> s pattern attribute:在提交事件期间,内置验证还通过<input>pattern属性使用正则表达式:

/^(\d{3}(\s|\-)|\(\d{3}\)\s)\d{3}(\-|\s)\d{4}$/mig

Regex101正则表达式101

 document.forms.main.addEventListener('input', hint); document.forms.main.addEventListener('change', validate); function hint(event) { const typedIn = event.target; const IO = this.elements; const inputs = [...IO.contact]; const messages = [...IO.message]; let idx = inputs.indexOf(typedIn); let msg = messages[idx]; if (typedIn.name === 'contact') { if (typedIn.validity.valid) { msg.textContent = ''; msg.classList.remove('error'); } } } function validate(event) { const typedIn = event.target; const IO = this.elements; const inputs = [...IO.contact]; const messages = [...IO.message]; let idx = inputs.indexOf(typedIn); let msg = messages[idx]; let txt = typedIn.value; const rgx = new RegExp(/^(\d{3}(\s|\-)|\(\d{3}\)\s)\d{3}(\-|\s)\d{4}$/, 'mig'); if (typedIn.name === 'contact') { if (!rgx.test(txt)) { msg.textContent = ''; msg.insertAdjacentHTML('afterbegin', ` <pre> <mark>${typedIn.value}</mark> is not a valid phone number. ex. (123) 456-7890 123-456-7890 123 456-7890 123 456 7890</pre>`); msg.classList.add('error'); } else { msg.textContent = ''; msg.classList.remove('error'); } } }
 html { font: 400 2ch/1.2 'Segoe UI' } form { display: flex; flex-flow: column nowrap; align-items: center; } input, button { font: inherit; } input { font-family: Consolas; width: 8em } input:valid { outline: 3px inset green; outline-offset: -2px; } input:invalid { outline: 3px inset red; outline-offset: -2px; color: red; font-weight: 900; } [name='message'] { display: inline-flex; align-self: flex-end; position: relative; z-index: -1; width: max-content; opacity: 0; font-size: 0; transition: 1s; } .error { z-index: 1; opacity: 1; font-size: 0.75rem; transition: 0.75s; transform: translate(-50%, 0); }
 <form id='main'> <label for='work'>Work:&ThickSpace;</label> <output name='message'></output> <input id='work' name='contact' type='tel' pattern="(\d{3}(\s|\-)|\(\d{3}\)\s)\d{3}(\-|\s)\d{4}" minlength='10' maxlength='14' size='12' optional> <label for='personal'>&ThickSpace;Personal:&ThickSpace;</label><output name='message'></output> <input id='personal' name='contact' type='tel' minlength='10' maxlength='14' size='12' required>&ThickSpace; <button>Done</button> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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