以 HTML5 形式显示 JavaScript 中的错误

新手上路,请多包涵

我有一个包含必填字段的 HTML5 表单:

 <form id="my_form">
    <input type="text" name="myfield1" required>
    <input type="text" name="myfield2" required>
    <input type="text" name="myfield3" required>
    <button type="button" id="my_button">Check</button>
</form>

另外,我有以下 jQuery 代码:

 $('#my_button').on('click', function() {
    if ($('#my_form').checkValidity() == false) {
       //show errors
    }
});

我想在 //show errors 行中强制显示 HTML5 错误。

原文由 Amparo 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 234
2 个回答

如果你想显示验证气泡,首先应该提交表单。将 button 的类型更改为 submit 并监听 submit 事件。

另请注意,jQuery 没有 checkValidity 方法,您应该首先获取原始 DOM 元素:

 // on submit event browser will validate the form and show the bubbles
$('#my_form').on('submit', function() {
    if (this.checkValidity() == false) {
        return false;
    }

   // ...

});

http://jsfiddle.net/m5duh44x/

原文由 Ram 发布,翻译遵循 CC BY-SA 3.0 许可协议

我有同样的问题,当您捕获 on.click 事件并对其执行某些操作时,不会出现 html5 气泡,例如在 html5 验证后继续使用 ajax。

我观察到如果在点击事件的捕获中有任何代码(一个简单的警报),它不会显示每个字段对应的html5的验证错误(气泡)

旨在验证现有的 html5 工作(这不会丢失并且工作正常)并且大于它可以捕获点击事件并继续从 javascript 执行操作

HTML5 要求在气泡必须出现的地方输入!

   <form id='form_insertar' method="post">
  <div class="modal-body">
    <div class="form-group">
      <label for="first_name">First Name</label>
      <input type="text" id="first_name" placeholder="First Name" class="form-control" maxlength="100" required />
    </div>

    <div class="form-group">
      <label for="last_name">Last Name</label>
      <input type="text" id="last_name" placeholder="Last Name" class="form-control" required />
    </div>

    <div class="form-group">
      <label for="email">Email Address</label>
      <input type="text" id="email" placeholder="Email Address" class="form-control" required/>
    </div>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
    <button type="submit" id='btn_addRecord' class="btn btn-primary">Add Record</button>
  </div>
  </form>

使它不出现的 JavaScript 代码:

 $(document).ready(function(){
    $('#btn_addRecord').on("click", function(event){
        //event.preventDefault();
        if ($("#form_insertar")[0].checkValidity()) {
            console.log('Validado el form: Inserta los datos con ajax!');
              //addRecord();
            return true;
        }
        if (!$("#form_insertar")[0].checkValidity()) {
            console.log('No validado el form: Devolvemos false y no hacemos nada. (LAMENTABLEMENTE HAY ALGO DESCONOCIDO POR LO QUE NO SE MUESTRAN LOS BUBBLES o ERRORES)');
            return false;
        }
        //alert('test');
    });

});

原文由 Robert Learning 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题