Javascript HTML5 表单必需属性。设置自定义验证消息?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5272433/
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
HTML5 form required attribute. Set custom validation message?
提问by Skizit
I've got the following HTML5 form: http://jsfiddle.net/nfgfP/
我有以下 HTML5 表单:http: //jsfiddle.net/nfgfP/
<form id="form" onsubmit="return(login())">
<input name="username" placeholder="Username" required />
<input name="pass" type="password" placeholder="Password" required/>
<br/>Remember me: <input type="checkbox" name="remember" value="true" /><br/>
<input type="submit" name="submit" value="Log In"/>
Currently when I hit enter when they're both blank, a popup box appears saying "Please fill out this field". How would I change that default message to "This field cannot be left blank"?
目前,当我在它们都为空白时按 Enter 键时,会出现一个弹出框,上面写着“请填写此字段”。我如何将该默认消息更改为“此字段不能留空”?
EDIT:Also note that the type password field's error message is simply *****
. To recreate this give the username a value and hit submit.
编辑:另请注意,类型密码字段的错误消息很简单*****
。要重新创建它,请给用户名一个值并点击提交。
EDIT: I'm using Chrome 10 for testing. Please do the same
编辑:我使用 Chrome 10 进行测试。请做同样的事
采纳答案by robertc
Use setCustomValidity
:
document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("This field cannot be left blank");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
I changed to vanilla JavaScriptfrom Mootools as suggested by @itpastornin the comments, but you should be able to work out the Mootools equivalent if necessary.
我按照@itpastorn在评论中的建议从 Mootools更改为 vanilla JavaScript,但如果需要,您应该能够计算出等效的 Mootools。
Edit
编辑
I've updated the code here as setCustomValidity
works slightly differently to what I understood when I originally answered. If setCustomValidity
is set to anything other than the empty string it will cause the field to be considered invalid; therefore you must clear it before testing validity, you can't just set it and forget.
我在这里更新了代码,因为它的setCustomValidity
工作原理与我最初回答时的理解略有不同。如果setCustomValidity
设置为空字符串以外的任何内容,则会导致该字段被视为无效;所以你必须在测试有效性之前清除它,你不能只是设置它并忘记它。
Further edit
进一步编辑
As pointed out in @thomasvdb's comment below, you need to clear the custom validity in some event outside of invalid
otherwise there may be an extra pass through the oninvalid
handler to clear it.
正如下面@thomasvdb 的评论中所指出的,您需要在某些事件之外清除自定义有效性,invalid
否则可能需要额外通过oninvalid
处理程序来清除它。
回答by Somnath Kadam
Here is the code to handle Custom Error Message in HTML5
这是在HTML5 中处理自定义错误消息的代码
<input type="text" id="username" required placeholder="Enter Name"
oninvalid="this.setCustomValidity('Enter User Name Here')"
oninput="this.setCustomValidity('')" />
This part is important because it hides the error message when the user inputs new data:
这部分很重要,因为它会在用户输入新数据时隐藏错误消息:
oninput="this.setCustomValidity('')"
回答by Ashwini Jain
It's very simple to control custom messages with the help of HTML5
event oninvalid
借助HTML5
事件控制自定义消息非常简单oninvalid
Here is code:
这是代码:
<input id="UserID" type="text" required="required"
oninvalid="this.setCustomValidity('Witinnovation')"
onvalid="this.setCustomValidity('')">
This is most important:
这是最重要的:
onvalid="this.setCustomValidity('')"
回答by kzh
Note:This no longer works in Chrome, not tested in other browsers. See edits below. This answer is being left here for historical reference.
注意:这在 Chrome 中不再有效,未在其他浏览器中测试。请参阅下面的编辑。这个答案留在这里以供历史参考。
If you feel that the validation string really should not be set by code, you can set you input element's title attribute to read "This field cannot be left blank". (Works in Chrome 10)
如果您觉得验证字符串真的不应该由代码设置,您可以将输入元素的标题属性设置为“此字段不能留空”。(适用于 Chrome 10)
title="This field should not be left blank."
See http://jsfiddle.net/kaleb/nfgfP/8/
见http://jsfiddle.net/kaleb/nfgfP/8/
And in Firefox, you can add this attribute:
在 Firefox 中,您可以添加此属性:
x-moz-errormessage="This field should not be left blank."
Edit
编辑
This seems to have changed since I originally wrote this answer. Now adding a title does not change the validity message, it just adds an addendum to the message. The fiddle above still applies.
自从我最初写这个答案以来,这似乎已经改变了。现在添加标题不会改变有效性消息,它只是向消息添加附录。上面的小提琴仍然适用。
Edit 2
编辑 2
Chrome now does nothing with the title attribute as of Chrome 51. I am not sure in which version this changed.
从 Chrome 51 开始,Chrome 现在对 title 属性不做任何处理。我不确定在哪个版本中发生了变化。
回答by Salar
By setting and unsetting the setCustomValidity
in the right time, the validation message will work flawlessly.
通过setCustomValidity
在正确的时间设置和取消设置,验证消息将完美无缺。
<input name="Username" required
oninvalid="this.setCustomValidity('Username cannot be empty.')"
onchange="this.setCustomValidity('')" type="text" />
I used onchange
instead of oninput
which is more general and occurs when the value is changed in any condition even through JavaScript.
我使用onchange
了oninput
更通用的代替which ,并且在任何条件下甚至通过 JavaScript 更改值时都会发生。
回答by Dharmendra Jha
It's very simple to control custom messages with the help of the HTML5
oninvalid
event
借助HTML5
oninvalid
事件控制自定义消息非常简单
Here is the code:
这是代码:
User ID
<input id="UserID" type="text" required
oninvalid="this.setCustomValidity('User ID is a must')">
回答by hleinone
I have made a small library to ease changing and translating the error messages. You can even change the texts by error type which is currently not available using title
in Chrome or x-moz-errormessage
in Firefox. Go check it out on GitHub, and give feedback.
我制作了一个小型库来简化更改和翻译错误消息。您甚至可以按错误类型更改文本,目前title
在 Chrome 或x-moz-errormessage
Firefox 中无法使用。去检查它在GitHub上,并提出反馈意见。
It's used like:
它的使用方式如下:
<input type="email" required data-errormessage-value-missing="Please input something">
There's a demo available at jsFiddle.
jsFiddle 上有一个演示。
回答by Rikin Patel
Try this one, its better and tested:
试试这个,它更好并经过测试:
HTML:
HTML:
<form id="myform">
<input id="email"
oninvalid="InvalidMsg(this);"
oninput="InvalidMsg(this);"
name="email"
type="email"
required="required" />
<input type="submit" />
</form>
JAVASCRIPT:
爪哇脚本:
function InvalidMsg(textbox) {
if (textbox.value === '') {
textbox.setCustomValidity('Required email address');
} else if (textbox.validity.typeMismatch){
textbox.setCustomValidity('please enter a valid email address');
} else {
textbox.setCustomValidity('');
}
return true;
}
Demo:
演示:
回答by Collin White
The easiest and cleanest way I've found is to use a data attribute to store your custom error. Test the node for validity and handle the error by using some custom html.
我发现的最简单和最干净的方法是使用数据属性来存储您的自定义错误。测试节点的有效性并使用一些自定义 html 处理错误。
le javascript
javascript
if(node.validity.patternMismatch)
{
message = node.dataset.patternError;
}
and some super HTML5
和一些超级 HTML5
<input type="text" id="city" name="city" data-pattern-error="Please use only letters for your city." pattern="[A-z ']*" required>
回答by Andrei Veshtard
The solution for preventing Google Chrome error messages on input each symbol:
防止在输入每个符号时出现 Google Chrome 错误消息的解决方案:
<p>Click the 'Submit' button with empty input field and you will see the custom error message. Then put "-" sign in the same input field.</p>
<form method="post" action="#">
<label for="text_number_1">Here you will see browser's error validation message on input:</label><br>
<input id="test_number_1" type="number" min="0" required="true"
oninput="this.setCustomValidity('')"
oninvalid="this.setCustomValidity('This is my custom message.')"/>
<input type="submit"/>
</form>
<form method="post" action="#">
<p></p>
<label for="text_number_1">Here you will see no error messages on input:</label><br>
<input id="test_number_2" type="number" min="0" required="true"
oninput="(function(e){e.setCustomValidity(''); return !e.validity.valid && e.setCustomValidity(' ')})(this)"
oninvalid="this.setCustomValidity('This is my custom message.')"/>
<input type="submit"/>
</form>