htmlvalidationrequired

Is it possible to customize an HTML <input required> attribute error message?


I am using the HTML required attribute to perform in-page validation.

<input type="text" required>

Please see this plunker: https://plnkr.co/edit/Swy4hFEewCYlnL0bJKq1?p=streamer

But I don't want to show the default error text, "Please fill out this field.", instead I want another customized message say "You cannot leave the xyz field empty. Blah, blah, blah"

How can I do this?


Solution

  • Try this code.

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

    A working JSFiddle can be found at http://jsfiddle.net/meghanagpal/B4hYG/622/