Set custom HTML5 required field validation message

Required field custom validation

I have one form with many input fields. I have put html5 validations

<input type="text" name="topicName" id="topicName" required />

when I submit the form without filling this textbox it shows default message like

"Please fill out this field"

Can anyone please help me to edit this message?

I have a javascript code to edit it, but it's not working

$(document).ready(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please enter Room Topic Title");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})


Email custom validations

I have following HTML form

<form id="myform">
<input id="email" name="email" type="email" />
<input type="submit" />
</form>


Validation messages I want like.

Required field: Please Enter Email Address
Wrong Email: 'testing@.com' is not a Valid Email Address. (here, entered email address displayed in textbox)

I have tried this.

function check(input) {
if(input.validity.typeMismatch){
input.setCustomValidity("'" + input.value + "' is not a Valid Email Address.");
}
else {
input.setCustomValidity("");
}
}

This function is not working properly, Do you have any other way to do this? It would be appreciated.

238519 次浏览

试试这个:

$(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("Please enter Room Topic Title");
};
}
})

我在 Chrome 和 FF 中测试过,它在两种浏览器中都能工作。

代码片段

由于这个答案得到了很多关注,下面是我想到的一个很好的可配置代码片段:

/**
* @author ComFreek <https://stackoverflow.com/users/603003/comfreek>
* @link https://stackoverflow.com/a/16069817/603003
* @license MIT 2013-2015 ComFreek
* @license[dual licensed] CC BY-SA 3.0 2013-2015 ComFreek
* You MUST retain this license header!
*/
(function (exports) {
function valOrFunction(val, ctx, args) {
if (typeof val == "function") {
return val.apply(ctx, args);
} else {
return val;
}
}


function InvalidInputHelper(input, options) {
input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));


function changeOrInput() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity("");
}
}


function invalid() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
}
}


input.addEventListener("change", changeOrInput);
input.addEventListener("input", changeOrInput);
input.addEventListener("invalid", invalid);
}
exports.InvalidInputHelper = InvalidInputHelper;
})(window);

用法

JsFiddle

<input id="email" type="email" required="required" />
InvalidInputHelper(document.getElementById("email"), {
defaultText: "Please enter an email address!",


emptyText: "Please enter an email address!",


invalidText: function (input) {
return 'The email address "' + input.value + '" is invalid!';
}
});

更多细节

  • 最初显示 defaultText
  • 当输入为空(被清除)时,将显示 emptyText
  • invalidText is displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)

您可以为这三个属性中的每一个分配一个字符串或函数。
如果分配一个函数,它可以接受对输入元素(DOM 节点)的引用,然后 必须的返回一个字符串,该字符串随后显示为错误消息。

Compatibility

测试范围:

  • Chrome Canary 47.0.2
  • IE 11
  • Microsoft Edge (使用截至28/08/2015的最新版本)
  • Firefox 40.0.3
  • Opera 31.0

旧答案

你可以在这里看到旧版本: https://stackoverflow.com/revisions/16069817/6

伙计,我从来没有在 HTML 5中这样做过,但是我会试试。看看 这把小提琴。

我使用了一些 jQuery、 HTML5原生事件和属性,以及一个关于输入标记的自定义属性(如果您试图验证代码,这可能会导致问题)。我没有在所有的浏览器测试,但我认为它可能工作。

这是使用 jQuery 进行字段验证的 JavaScript 代码:

$(document).ready(function()
{
$('input[required], input[required="required"]').each(function(i, e)
{
e.oninput = function(el)
{
el.target.setCustomValidity("");


if (el.target.type == "email")
{
if (el.target.validity.patternMismatch)
{
el.target.setCustomValidity("E-mail format invalid.");


if (el.target.validity.typeMismatch)
{
el.target.setCustomValidity("An e-mail address must be given.");
}
}
}
};


e.oninvalid = function(el)
{
el.target.setCustomValidity(!el.target.validity.valid ? e.attributes.requiredmessage.value : "");
};
});
});

很好。下面是简单的表单 html:

<form method="post" action="" id="validation">
<input type="text" id="name" name="name" required="required" requiredmessage="Name is required." />
<input type="email" id="email" name="email" required="required" requiredmessage="A valid E-mail address is required." pattern="^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9]+$" />


<input type="submit" value="Send it!" />
</form>

属性 requiredmessage是我讨论过的自定义属性。您可以为每个必需的字段设置消息,因为 jQuery 将在显示错误消息时从中获取消息。您不必在 JavaScript 上设置每个字段,jQuery 可以为您做到这一点。那个正则表达式看起来很好(至少它阻塞了你的 testing@.com!哈哈)

正如你在小提琴上看到的,我对提交表单事件(这个要记录在案,也准备好了)做了一个额外的验证:

$("#validation").on("submit", function(e)
{
for (var i = 0; i < e.target.length; i++)
{
if (!e.target[i].validity.valid)
{
window.alert(e.target.attributes.requiredmessage.value);
e.target.focus();
return false;
}
}
});

我希望这能起作用,或者对你有帮助。

您可以这样做,在相同类型的所有输入中为“无效”设置一个事件侦听器,或者只设置一个事件侦听器,这取决于您需要什么,然后设置适当的消息。

[].forEach.call( document.querySelectorAll('[type="email"]'), function(emailElement) {
emailElement.addEventListener('invalid', function() {
var message = this.value + 'is not a valid email address';
emailElement.setCustomValidity(message)
}, false);


emailElement.addEventListener('input', function() {
try{emailElement.setCustomValidity('')}catch(e){}
}, false);
});

脚本的第二部分,有效性消息将被重置,因为否则不可能提交表单: 例如,这将防止消息被触发,即使电子邮件地址已被更正。

另外,您不必根据需要设置输入字段,因为一旦您开始输入输入,就会触发“无效”。

Here is a fiddle for that: http://jsfiddle.net/napy84/U4pB7/2/ 希望能帮上忙!

HTML:

<form id="myform">
<input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);"  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;
}

演示:

Http://jsfiddle.net/patelriki13/sqq8e/

只需要获取元素并使用 setCustomVality 方法。

例子

var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');

在每个输入标签中使用属性“ title”,并在其上写一条消息

这对我很有效:

jQuery(document).ready(function($) {
var intputElements = document.getElementsByTagName("INPUT");
for (var i = 0; i < intputElements.length; i++) {
intputElements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
if (e.target.name == "email") {
e.target.setCustomValidity("Please enter a valid email address.");
} else {
e.target.setCustomValidity("Please enter a password.");
}
}
}
}
});

和我使用它的形式(截断) :

<form id="welcome-popup-form" action="authentication" method="POST">
<input type="hidden" name="signup" value="1">
<input type="email" name="email" id="welcome-email" placeholder="Email" required></div>
<input type="password" name="passwd" id="welcome-passwd" placeholder="Password" required>
<input type="submit" id="submitSignup" name="signup" value="SUBMIT" />
</form>

enter image description here

您可以简单地使用 onvoid 属性来实现这一点, 检查这个演示代码

<form>
<input type="email" pattern="[^@]*@[^@]" required oninvalid="this.setCustomValidity('Put  here custom message')"/>
<input type="submit"/>
</form>

enter image description here

代码演示: https://codepen.io/akshaykhale1992/pen/yLNvOqP

您可以简单地使用 无效 =”属性,并绑定 This. setCustomVality () eventListener!

Here is my demo codes!(you can run it to check out!) enter image description here

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>oninvalid</title>
</head>
<body>
<form action="https://www.google.com.hk/webhp?#safe=strict&q=" method="post" >
<input type="email" placeholder="xgqfrms@email.xyz" required="" autocomplete="" autofocus="" oninvalid="this.setCustomValidity(`This is a customlised invalid warning info!`)">
<input type="submit" value="Submit">
</form>
</body>
</html>

参考链接

http://caniuse.com/#feat=form-validation

Https://www.w3.org/tr/html51/sec-forms.html#sec-constraint-validation

您可以添加此脚本以显示您自己的消息。

 <script>
input = document.getElementById("topicName");


input.addEventListener('invalid', function (e) {
if(input.validity.valueMissing)
{
e.target.setCustomValidity("Please enter topic name");
}
//To Remove the sticky error message at end write




input.addEventListener('input', function (e) {
e.target.setCustomValidity('');
});
});


</script>

对于其他验证,如模式不匹配,您可以添加额外的 if else 条件

喜欢

else if (input.validity.patternMismatch)
{
e.target.setCustomValidity("Your Message");
}

there are other validity conditions like rangeOverflow,rangeUnderflow,stepMismatch,typeMismatch,valid

按照以下方式在 onvalid属性上使用它

oninvalid="this.setCustomValidity('Special Characters are not allowed')