输入类型不是“提交”时的HTML5验证 [英] HTML5 validation when the input type is not "submit"

查看:112
本文介绍了输入类型不是“提交”时的HTML5验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用HTML5验证字段。我在点击按钮时使用JavaScript提交表单。但HTML5验证不起作用。只有当输入类型为 提交 。除了使用JavaScript验证或将类型更改为 submit



这是HTML代码:

 < input type =textid =examplename =examplevalue =required> 
< button type =buttononclick =submitform()id =save>保存< / button>

我在函数 submitform()中提交表单HTML5表单验证过程仅限于通过提交按钮提交表单的情况。HTML5表单验证过程仅限于通过提交按钮提交表单的情况。 表单提交算法明确表示不执行验证当通过 submit()方法提交表单时。显然,这个想法是,如果你通过JavaScript提交表单,你应该进行验证。然而,你可以请求(静态)表单验证对照定义的约束通过HTML5属性,使用 checkValidity()方法。如果您想显示与浏览器在HTML5表单验证中显示的相同的错误消息,恐怕您需要检查所有受限字段,因为 validityMessage 财产是领域(控制)的财产,而不是形式。在单个约束字段的情况下,正如所示的情况,这当然是微不足道的:

  function submitform(){ 
var f = document.getElementsByTagName('form')[0];
if(f.checkValidity()){
f.submit();
} else {
alert(document.getElementById('example')。validationMessage);
}
}


I'm using HTML5 for validating fields. I'm submitting the form using JavaScript on a button click. But the HTML5 validation doesn't work. It works only when then input type is submit. Can we do anything other than using JavaScript validation or changing the type to submit?

This is the HTML code:

<input type="text" id="example" name="example" value="" required>
<button type="button"  onclick="submitform()" id="save">Save</button>

I'm submitting the form in the function submitform().

解决方案

The HTML5 form validation process is limited to situations where the form is being submitted via a submit button. The Form submission algorithm explicitly says that validation is not performed when the form is submitted via the submit() method. Apparently, the idea is that if you submit a form via JavaScript, you are supposed to do validation.

However, you can request (static) form validation against the constraints defined by HTML5 attributes, using the checkValidity() method. If you would like to display the same error messages as the browser would do in HTML5 form validation, I’m afraid you would need to check all the constrained fields, since the validityMessage property is a property of fields (controls), not the form. In the case of a single constrained field, as in the case presented, this is trivial of course:

function submitform() {
  var f = document.getElementsByTagName('form')[0];
  if(f.checkValidity()) {
    f.submit();
  } else {
    alert(document.getElementById('example').validationMessage);
  }
}

这篇关于输入类型不是“提交”时的HTML5验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆