我可以从 javascript 中标记一个无效的字段吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10777970/
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
Can I mark a field invalid from javascript?
提问by Svish
From reading this postI have found that there are some pseudo classes for 'valid' and 'invalid' input values introduced to HTML5.
通过阅读这篇文章,我发现 HTML5 中引入了一些用于“有效”和“无效”输入值的伪类。
Is there a way I can mark an input field as invalid/valid from javascript? Or alternatively, can I override the validation method used?
有没有办法可以从javascript将输入字段标记为无效/有效?或者,我可以覆盖使用的验证方法吗?
回答by dajavax
You could use the customValidity function for this purpose.
为此,您可以使用 customValidity 函数。
If you add a customValidity message to the field, it becomes invalid. When you set the message as an empty string, it becomes valid again (unless it is invalid because of other reasons).
如果您向该字段添加 customValidity 消息,它就会变得无效。当您将消息设置为空字符串时,它再次变为有效(除非由于其他原因无效)。
field.setCustomValidity("Invalid field.");
will make the field invalid.
field.setCustomValidity("Invalid field.");
将使该字段无效。
field.setCustomValidity("");
will make the field valid unless it fails an HTML5 constraint.
field.setCustomValidity("");
将使该字段有效,除非它未通过 HTML5 约束。
回答by Raekye
Edit: Someone clarified that you're looking for "valid" "invalid" attributes for DOM.
编辑:有人澄清说您正在寻找 DOM 的“有效”“无效”属性。
I would add attributes to each tag using dom_object.setAttribute("isvalid", "true")
. You could also have a central validation function which updates these attributes each time (and use dom_object.getAttribute("isvalid")
each time).
我会使用dom_object.setAttribute("isvalid", "true")
. 您还可以有一个中央验证功能,每次更新这些属性(并dom_object.getAttribute("isvalid")
每次使用)。
You could run this function each time an element loses focus, or whenever you want.
您可以在每次元素失去焦点时或在需要时运行此函数。
Not exactly elegant, but unfortunately there's no "pseudo" support with javascript and HTML5 now.
不完全优雅,但不幸的是现在没有对 javascript 和 HTML5 的“伪”支持。
If I understand your question, you can do validation with Javascript. However, be warned that it is very easy to circumvent client side validation, especially javascript validation. You should never trust client data and always do checking on the server side.
如果我理解您的问题,您可以使用 Javascript 进行验证。但是,请注意,很容易绕过客户端验证,尤其是 javascript 验证。您永远不应该相信客户端数据,并始终在服务器端进行检查。
For example, I could easily find element IDs by inspecting the source code, then do document.getElementById('some_id').setAttribute('max', new_number)
to change the max value (this was one of the entries from your link).
例如,我可以通过检查源代码轻松找到元素 ID,然后document.getElementById('some_id').setAttribute('max', new_number)
更改最大值(这是您链接中的条目之一)。
There are various ways to do it, so I'll try to give you the general idiom.
有多种方法可以做到这一点,所以我将尝试为您提供通用的习语。
You can grab the value by doing document.getElementById('form_element_id').value
(make sure you give the form a name
which is sent to the server, and an id
which is used by javascript). For textareas, you can use .innerHTML
.
您可以通过执行获取值document.getElementById('form_element_id').value
(确保提供name
发送到服务器的表单 a和id
javascript 使用的表单)。对于文本区域,您可以使用.innerHTML
.
Then you have the value in a variable, there are various ways to check it.
然后你有一个变量的值,有多种方法可以检查它。
For example, you could do if (parseInt(my_value) < 0) //error
.
You could also use regular expressions, I won't explain it all but you could start here http://www.w3schools.com/jsref/jsref_obj_regexp.asp. I know w3schools isn't the best source but I find it an okay place to start.
例如,您可以执行if (parseInt(my_value) < 0) //error
. 您也可以使用正则表达式,我不会全部解释,但您可以从http://www.w3schools.com/jsref/jsref_obj_regexp.asp开始。我知道 w3schools 不是最好的来源,但我发现它是一个不错的起点。
Now for the validation part: add onsubmit="return validateForm()
to your form tag where validateForm() is the function which does all the checking. And the function just returns true
if valid and false
otherwise. This overrides the default validation function(which by default does nothing).
现在是验证部分:添加onsubmit="return validateForm()
到您的表单标签中,其中 validateForm() 是执行所有检查的函数。并且该函数仅true
在有效时返回,false
否则返回。这将覆盖默认验证功能(默认情况下不执行任何操作)。
So in the above example, //error
would be replaced by return false
. You can do other things too; such as alert the error then return false. You could also use javascript to highlight the invalid fields (not sure if this is what you mean by "mark an input field as invalid/valid from javascript")
所以在上面的例子中,//error
将被替换为return false
. 你也可以做其他事情;例如警告错误然后返回false。您还可以使用 javascript 突出显示无效字段(不确定这是否是您所说的“从 javascript 将输入字段标记为无效/有效”的意思)
Of course, if you don't want to check all the fields you only have to return true if the certain ones pass. Again, you shouldn't rely on this, but if you're only out to deter average people then it's an easy solution.
当然,如果您不想检查所有字段,则只需在某些字段通过时返回 true。同样,您不应该依赖于此,但是如果您只是为了威慑普通人,那么这是一个简单的解决方案。
回答by elclanrs
Is there a way I can mark an input field as invalid/valid from javascript?
有没有办法可以从javascript将输入字段标记为无效/有效?
Unfortunately, you can't style pseudo classes in JavaScript, since they're not real elements, they don't exist in the actual DOM.
不幸的是,您不能在 JavaScript 中设置伪类的样式,因为它们不是真正的元素,它们不存在于实际的 DOM 中。
With vanilla JavaScript you'd use the validation API.
使用 vanilla JavaScript,您将使用验证 API。
In jQuery you can simply do this, http://jsfiddle.net/elclanrs/Kak6S/
在 jQuery 中,您可以简单地执行此操作,http://jsfiddle.net/elclanrs/Kak6S/
if ( $input.is(':invalid') ) { ... }
Or alternatively, can I override the validation method used?
或者,我可以覆盖使用的验证方法吗?
If you're using HTML5 validation, then stick to the markup. Otherwise, you can disable HTML5 validation with $form.attr('novalidate', 'novalidate')
and use JS to validate your fields, and then adding valid
or invalid
classes where needed. I made a pluginthat works like this to support non HTML5 browsers.
如果您使用 HTML5 验证,请坚持使用标记。否则,您可以禁用 HTML5 验证$form.attr('novalidate', 'novalidate')
并使用 JS 来验证您的字段,然后在需要的地方添加valid
或invalid
类。我制作了一个这样的插件来支持非 HTML5 浏览器。