Javascript 一种检查 HTML5 表单有效性的方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5846382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:10:34  来源:igfitidea点击:

a way to check validity of HTML5 forms?

javascriptformshtmldom

提问by Henry

Is it possible to check if an input element of an html5 form is valid based on the pattern I set for it? I know the psuedo class stuff.. but i'm hoping something like: document.getElementById('petitionName').validcan return trueor false..

是否可以根据我为其设置的模式检查 html5 表单的输入元素是否有效?我知道伪类的东西..但我希望像这样: document.getElementById('petitionName').valid可以返回truefalse..

I really hope I don't need to create javascript to re-verify this stuff.

我真的希望我不需要创建 javascript 来重新验证这些东西。

回答by alexander farkas

there are two ways to check the validity.

有两种方法可以检查有效性。

  1. inputElement.checkValidity()returns trueor false
  2. inputElement.validityreturns the validity-state object. inputElement.validity.validreturns true/false
  1. inputElement.checkValidity()返回truefalse
  2. inputElement.validity返回有效性状态对象。inputElement.validity.valid返回true/false

Instead of using keyup, you can also use the 'input' event. All browser, which have implemented the constraint validation API, have also implemented the input-event.

除了使用 keyup,您还可以使用 'input' 事件。所有实现了约束验证 API 的浏览器也都实现了输入事件。

If you are using option 1 above, Opera has a bug here and will show its validation hint. So you should use 2.

如果您使用上面的选项 1,Opera 有一个错误,将显示其验证提示。所以你应该使用2。

I have created a html5 forms library, which implements all unknown features to incapable browsers + fixes issues in HTML5 browsers. So everything works like defined in the spec, but it's built on top of jQuery. (http://afarkas.github.com/webshim/demos/index.html).

我创建了一个 html5 表单库,它为无法运行的浏览器实现了所有未知功能 + 修复了 HTML5 浏览器中的问题。所以一切都像规范中定义的那样工作,但它建立在 jQuery 之上。(http://afarkas.github.com/webshim/demos/index.html)。

回答by alex

You can use the patternattribute.

您可以使用pattern属性

It will validate it client side, so no need to validate it again client side.

它将在客户端对其进行验证,因此无需再次在客户端进行验证。

Example

例子

jsFiddle.

js小提琴

But, make sure you do it again server side.

但是,请确保您再次在服务器端执行此操作。

Also note, because browser compatibility is quite poor right now, JavaScript is the norm for validating client side.

另请注意,由于目前浏览器兼容性很差,因此 JavaScript 是验证客户端的标准。