【问题标题】:Javascript form validation: custom error messageJavascript 表单验证:自定义错误消息
【发布时间】:2018-07-29 08:57:41
【问题描述】:

https://codepen.io/durja/pen/BPmmyR

我正在尝试使用 html 中的约束 api 为表单实现自定义错误消息。下面是我的代码,我遇到了一个问题,在输入错误的输入并再次更正后,验证消息仍然出现。我不确定我错过了什么。我什至尝试使用 checkValidity() 方法检查有效性,即使输入的模式正确,该方法也会返回 false。

const fp = document.getElementById('quantity');
const ide = document.getElementById('ide_pref');

fp.addEventListener('input',e => {
    console.log(e.target.value);
   if(fp.validity.rangeOverflow) {
       fp.setCustomValidity('Custom message: greater than 100 not allowed.');
   }
});

ide.addEventListener('input',e => {
  console.log(e.target.value);
  console.log(ide.checkValidity());
  if(ide.validity.patternMismatch) {
    ide.setCustomValidity('enter exactly webstorm OR vscode');
  }
})

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    HTMLSelectElement.setCustomValidity()

    HTMLSelectElement.setCustomValidity() 方法将选择元素的自定义有效性消息设置为指定消息。使用空字符串表示该元素没有自定义有效性错误。

    您目前从未重置自定义有效性消息,因此只要输入无效,它就会永远保持'Custom message: greater than 100 not allowed.'(或其他元素的其他消息)。插入以空字符串调用setCustomValidityelse 语句(如果没有rangeOverflow 或没有patternMismatch)以清除错误消息,以防单击按钮时存在错误消息:

    const fp = document.getElementById('quantity');
    const ide = document.getElementById('ide_pref');
    
    fp.addEventListener('input', e => {
      if (fp.validity.rangeOverflow) {
        fp.setCustomValidity('Custom message: greater than 100 not allowed.');
      } else {
        fp.setCustomValidity('');
      }
    });
    
    ide.addEventListener('input', e => {
      if (ide.validity.patternMismatch) {
        ide.setCustomValidity('enter exactly webstorm OR vscode');
      } else {
        ide.setCustomValidity('');
      }
    })
    .u {
      margin-bottom: 15px;
    }
    
    .u:invalid {
      border: 2px solid orangered;
    }
    
    .u:valid {
      border: 2px solid greenyellow;
    }
    
    .btn {
      border: none;
      padding: 10px;
      border-radius: 8px;
      margin-top: 10px;
    }
    
    :focus {
      outline-color: gray;
    }
    <form action="#" method="get">
      <div>
        <label for="ide_pref">Would you prefer webstorm or vscode?</label>
        <input required class="u" type="text" pattern="webstorm|vscode" id="ide_pref" name="ide_pref"><br>
        <label for="quantity">How many licences would you like?</label>
        <input required class="u" type="number" min="1" max="100" id="quantity" name="lic_quantity"><br>
        <button class="btn" type="submit">Submit</button>
      </div>
    </form>

    【讨论】:

      猜你喜欢
      • 2011-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多