Javascript 设置自定义 HTML5 必填字段验证消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13798313/
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-24 12:55:39  来源:igfitidea点击:

Set custom HTML5 required field validation message

javascriptjqueryhtml

提问by Sumit Bijvani

Required field custom validation

必填字段自定义验证

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

我有一个包含许多输入字段的表单。我已经放了 html5 验证

<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"

"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

我有一个 javascript 代码来编辑它,但它不起作用

$(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

我有以下 HTML 表单

<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:'[email protected]' is not a Valid Email Address. (here, entered email address displayed in textbox)

必填字段:请输入电子邮件地址
错误的电子邮件:[email protected]”不是有效的电子邮件地址。(此处,输入的电子邮件地址显示在文本框中

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.

此功能无法正常工作,您还有其他方法吗?将不胜感激。

回答by ComFreek

Code snippet

代码片段

Since this answer got very much attention, here is a nice configurable snippet I came up with:

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

/**
  * @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);

Usage

用法

jsFiddle

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!';
  }
});

More details

更多细节

  • defaultTextis displayed initially
  • emptyTextis displayed when the input is empty (was cleared)
  • invalidTextis displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)
  • defaultText最初显示
  • emptyText当输入为空时显示(被清除)
  • invalidText当输入被浏览器标记为无效时显示(例如当它不是有效的电子邮件地址时)

You can either assign a string or a function to each of the three properties.
If you assign a function, it can accept a reference to the input element (DOM node) and it mustreturn a string which is then displayed as the error message.

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

Compatibility

兼容性

Tested in:

测试于:

  • Chrome Canary 47.0.2
  • IE 11
  • Microsoft Edge (using the up-to-date version as of 28/08/2015)
  • Firefox 40.0.3
  • Opera 31.0
  • 铬金丝雀 47.0.2
  • 浏览器 11
  • Microsoft Edge(使用截至 28/08/2015 的最新版本)
  • 火狐 40.0.3
  • 歌剧 31.0


Old answer

旧答案

You can see the old revision here: https://stackoverflow.com/revisions/16069817/6

您可以在此处查看旧版本:https: //stackoverflow.com/revisions/16069817/6

回答by Akshay Khale

You can simply achieve this using oninvalid attribute, checkout this demo code

您可以使用 oninvalid 属性简单地实现此目的,请查看此演示代码

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

enter image description here

在此处输入图片说明

Codepen Demo: https://codepen.io/akshaykhale1992/pen/yLNvOqP

Codepen 演示:https://codepen.io/akshaykhale1992/pen/yLNvOqP

回答by Rikin Patel

HTML:

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;
}

Demo :

演示:

http://jsfiddle.net/patelriki13/Sqq8e/

http://jsfiddle.net/patelriki13/Sqq8e/

回答by Levi Botelho

Try this:

尝试这个:

$(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");
        };
    }
})

I tested this in Chrome and FF and it worked in both browsers.

我在 Chrome 和 FF 中对此进行了测试,并且在两种浏览器中都可以使用。

回答by DontVoteMeDown

Man, I never have done that in HTML 5 but I'll try. Take a look on this fiddle.

伙计,我从未在 HTML 5 中这样做过,但我会尝试。看看这个小提琴。

I have used some jQuery, HTML5 native events and properties and a custom attribute on input tag(this may cause problem if you try to validade your code). I didn't tested in all browsers but I think it may work.

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

This is the field validation JavaScript code with jQuery:

这是使用 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 : "");
        };
    });
});

Nice. Here is the simple form html:

好的。这是简单的表单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>

The attribute requiredmessageis the custom attribute I talked about. You can set your message for each required field there cause jQuery will get from it when it will display the error message. You don't have to set each field right on JavaScript, jQuery does it for you. That regex seems to be fine(at least it block your [email protected]! haha)

属性requiredmessage就是我讲的自定义属性。您可以为每个必填字段设置消息,因为 jQuery 会在显示错误消息时从中获取。您不必在 JavaScript 上正确设置每个字段,jQuery 会为您完成。那个正则表达式似乎很好(至少它阻止了你[email protected]!哈哈)

As you can see on fiddle, I make an extra validation of submit form event(this goes on document.ready too):

正如你在小提琴上看到的,我对提交表单事件进行了额外的验证(这也发生在 document.ready 上):

$("#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;
        }
    }
});

I hope this works or helps you in anyway.

我希望这对您有用或对您有所帮助。

回答by davidcondrey

This works well for me:

这对我很有效:

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.");
                }
            }
        }
    }
});

and the form I'm using it with (truncated):

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

<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

在此处输入图片说明

回答by iglesiasedd

Use the attribute "title" in every input tag and write a message on it

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

回答by Mimo

You can do this setting up an event listener for the 'invalid' across all the inputs of the same type, or just one, depending on what you need, and then setting up the proper message.

您可以根据您的需要为所有相同类型的输入或仅一个输入设置“无效”的事件侦听器,然后设置正确的消息。

[].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);
    });

The second piece of the script, the validity message will be reset, since otherwise won't be possible to submit the form: for example this prevent the message to be triggered even when the email address has been corrected.

脚本的第二部分,有效性消息将被重置,否则将无法提交表单:例如,即使电子邮件地址已更正,这也会阻止触发消息。

Also you don't have to set up the input field as required, since the 'invalid' will be triggered once you start typing in the input.

此外,您不必按要求设置输入字段,因为一旦您开始输入,就会触发“无效”。

Here is a fiddle for that: http://jsfiddle.net/napy84/U4pB7/2/Hope that helps!

这是一个小提琴:http: //jsfiddle.net/napy84/U4pB7/2/希望有帮助!

回答by LuisRBarreras

Just need to get the element and use the method setCustomValidity.

只需要获取元素并使用 setCustomValidity 方法即可。

Example

例子

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

回答by xgqfrms

you can just simply using the oninvalid="attribute, with the bingding the this.setCustomValidity()eventListener!

你可以简单地使用oninvalid="属性,绑定this.setCustomValidity()事件监听器!

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="[email protected]" required="" autocomplete="" autofocus="" oninvalid="this.setCustomValidity(`This is a customlised invalid warning info!`)">
        <input type="submit" value="Submit">
    </form>
</body>
</html>

reference link

参考链接

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

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

https://www.w3.org/TR/html51/sec-forms.html#sec-constraint-validation

https://www.w3.org/TR/html51/sec-forms.html#sec-constraint-validation