【问题标题】:HTML pattern not working for formatted phone numberHTML 模式不适用于格式化的电话号码
【发布时间】:2020-06-29 03:20:51
【问题描述】:

根据我的正则表达式测试,这应该通过模式测试...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>

【问题讨论】:

  • 也尝试了 `pattern="\D*(\d\D*){10}"` 并且它有效,但它有一个错误。如果我以错误的值提交,则每次尝试失败后都会失败。在铬。

标签: javascript html regex


【解决方案1】:

基本上我对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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2015-05-16
    • 1970-01-01
    相关资源
    最近更新 更多