1

我正在使用 HTML5 required 属性来执行页面内验证。

<input type="text" required>

请看这个插件:http://plnkr.co/edit/Swy4hFEewCYlnL0bJKq1?p= streamer

但我不想显示默认的错误文本"Please fill out this field.",而是想要另一条自定义消息说"You cannot leave the xyz field empty. Blah, blah, blah"

我该怎么做?甚至可能吗?

网上资料好像不够多。

请指导。

4

2 回答 2

2

试试这个代码 HTML

<form action="">
    <input id="email" type="email" required="required" />
    <input type="submit" id="btnSubmit" />
</form>

Javascript

(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 {
               console.log("INVALID!"); input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
            }
        }

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



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

可以在http://jsfiddle.net/meghanagpal/B4hYG/622/找到工作小提琴

于 2015-08-11T17:10:23.440 回答
-1

当然可以,只需一点 Javascript。您可以使用HTMLInputElement.setCustomValidity(String). 当它设置为任何非空字符串时,所有权<input>将不会验证。您可以在change事件或类似事件中调用它;如果您通过自己的代码决定<input>无效,只需设置消息。如果您认为一切正常,则将其设置为""(空String)。

希望有帮助。

于 2015-08-11T16:05:10.733 回答