繁体   English   中英

HTML 模式不适用于格式化的电话号码

[英]HTML pattern not working for formatted phone number

根据我的正则表达式测试,这应该通过模式测试... https://regex101.com/r/dT3vQC/1

然而,有些事情出错了。 请帮助我理解这一点。

 function formatPhone(obj) { var numbers = obj.value.replace(/\\D/g, ''), char = { 0: '(', 3: ') ', 6: ' - ' }; obj.value = ''; for (var i = 0; i < numbers.length; i++) { obj.value += (char[i] || '') + numbers[i]; } console.log(obj.value) }
 <form> <input required type="tel" name="phone" id="phone" placeholder="(xxx) xxx - xxxx" onblur="formatPhone(this);" onkeypress="formatPhone(this);" pattern="\\([0-9]{3}\\)\\s[0-9]{3}\\s-\\s[0-9]{4}" oninvalid="this.setCustomValidity('please enter 10 digit number')"> <button>check</button> </form>

基本上我对setCustomValidity的 api 感到困惑,如果你将它设置为一个空字符串,这意味着它不会被触发。 如果设置了该值,它将在每次提交时触发。 这是一个工作示例。

 function formatPhone(phoneInput) { var numbers = phoneInput.value.replace(/\\D/g, ''), char = { 0: '(', 3: ') ', 6: ' - ' }; phoneInput.value = ''; for (var i = 0; i < numbers.length; i++) { phoneInput.value += (char[i] || '') + numbers[i]; } } function checkPhone(phoneInput) { var formatted = phoneInput.value.replace(/\\D/g, ''); if (formatted.length !== 10) { phoneInput.setCustomValidity('please enter 10 digit number') } else { phoneInput.setCustomValidity(""); // be sure to leave this empty! } }
 <form> <input required type="tel" name="phone" id="phone" placeholder="(xxx) xxx - xxxx" oninput="checkPhone(this);" onblur="formatPhone(this);" onkeypress="formatPhone(this);"> <button>check</button> </form>

暂无
暂无

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

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