[英]HTML pattern not working for formatted phone number
according to my regex test this should pass the pattern test... https://regex101.com/r/dT3vQC/1根据我的正则表达式测试,这应该通过模式测试... https://regex101.com/r/dT3vQC/1
However something is going wrong.然而,有些事情出错了。 Please help me understand this.请帮助我理解这一点。
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>
Basically I was confused about the api for setCustomValidity
if you set it to an empty string that means it isn't going to fire.基本上我对setCustomValidity
的 api 感到困惑,如果你将它设置为一个空字符串,这意味着它不会被触发。 If that value is set it will fire on every submit.如果设置了该值,它将在每次提交时触发。 Here is a working example.这是一个工作示例。
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.