120

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.

G5W
  • 36,531
  • 10
  • 47
  • 80
Sumit Bijvani
  • 8,154
  • 17
  • 50
  • 82
  • 1
    What do you mean 'not working'? Is it giving an error? Open Chrome's developer tools or Firefox's Firebug and see if there's a JavaScript error. – Osiris Dec 10 '12 at 09:42
  • is there any other way to do this? – Sumit Bijvani Dec 10 '12 at 09:51
  • Can you post more code? What you have posted isn't enough to help you. And what browser(s) are you testing this in? – Levi Botelho Apr 18 '13 at 05:54
  • @LeviBotelho I have posted whole code, and I am testing this in Firefox and chrome – Sumit Bijvani Apr 18 '13 at 05:56
  • Alright, but what version of FF and Chrome? – Levi Botelho Apr 18 '13 at 07:44
  • Latest Firefox 20.0 and Chrome 25 – Sumit Bijvani Apr 18 '13 at 07:47
  • +1 for the question! I've been wanting to do this as well! – Rutwick Gangurde Apr 20 '13 at 02:31
  • 3
    @SumitBijvani What do you mean by 'Looking for more better answers'? I'll improve my answer if you would tell me what parts are wrong / not sufficient. – ComFreek May 26 '13 at 10:31
  • @ComFreek your answer is good, but I just looking for other examples, because I am writing a blog on HTML validations that's why I want different-different examples. also thank you very much for your previous bounty answer. – Sumit Bijvani May 27 '13 at 09:11
  • @SumitBijvani I just want to note that all answers are licensed under [CC BY-SA 3.0](http://creativecommons.org/licenses/by-sa/3.0/) thus you should (have to) give credit in your blog article ;) – ComFreek Jun 22 '13 at 13:31
  • Possible duplicate of [HTML5 form required attribute. Set custom validation message?](https://stackoverflow.com/questions/5272433/html5-form-required-attribute-set-custom-validation-message) – Gyrfalcon Jun 29 '18 at 16:30

12 Answers12

119

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

<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

  • defaultText is displayed initially
  • emptyText is displayed when the input is empty (was cleared)
  • invalidText is displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)

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 must return a string which is then displayed as the error message.

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

Old answer

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

Community
  • 1
  • 1
ComFreek
  • 29,044
  • 18
  • 104
  • 156
  • 1
    thanks... your custom validation for wrong email is working but, for required field it show me message `please fill out this field` can you change this message to `Please enter email address` – Sumit Bijvani Apr 18 '13 at 05:59
  • @SumitBijvani No problem, that behaviour occurs because we're setting `setCustomValidity()` for empty emails only after the *blur* event has fired once thus we just need to call it at DOM loading, too. See updated example/jsFiddle. – ComFreek Apr 18 '13 at 15:22
  • @SumitBijvani I've also fixed some flaws, see my code comments, please. Feel free to ask questions ;) – ComFreek Apr 18 '13 at 15:27
  • 1
    thanks for updated jsFiddle, validations are working fine, but there is one problem when I enter real email address, then also validation says, email address is invalid – Sumit Bijvani Apr 23 '13 at 05:54
  • @SumitBijvani Should be fixed now. The problem was that the code was using the `blur` instead of the `input` event (see comments). – ComFreek Apr 23 '13 at 12:47
  • @ComFreek is there a way to display validation-bubble-message without using the required tag? – User7291 Sep 20 '13 at 11:10
  • @JocelyneElKhoury What is your use case? Have a look at this link: http://stackoverflow.com/questions/11866910/how-to-force-a-html5-form-validation-without-submitting-it-via-javascript-jquery – ComFreek Sep 20 '13 at 11:22
  • @ComFreek i'm using asp.net i have a div for login and one for the register so i have just ONE FORM but 2 submit buttons so i need to display validation-bubble-message without using the required tag because if i use required tag on a textbox in the login div and click on the submit of the register div it will raise a validation – User7291 Sep 20 '13 at 11:49
  • @JocelyneElKhoury You could use `elem.required = false` in a click event handler of your second button. – ComFreek Sep 20 '13 at 12:05
  • @ComFreek i tried using this `Dim tbUserName As TextBox =Page.FindControl("username") tbUserName.required = False` but required is not a member of textbox in vb – User7291 Sep 20 '13 at 12:42
  • @JocelyneElKhoury This is JavaScript code which is run by the browser! You cannot try to run it in vB. Do you have a vB .NET formular or a HTML formular? – ComFreek Sep 20 '13 at 15:28
  • hello@hello.com does not validate... anything I put in the fiddle is not working... – Mariano Argañaraz Nov 06 '13 at 13:29
  • @MarianoArgañaraz Again sorry for the bugs. I removed my previous comment because it also linked to a buggy version of the fiddle. The jsFiddle link contained in the answer should be right at the time of writing. – ComFreek Nov 06 '13 at 14:16
  • 1
    This works great. I wanted the HTML5 "required" functionality to also validate against only whitespace chars being submitted (whereas by default it only validates against an empty string being submitted). So I changed the two lines with `if (input.value == "") {`, to instead read `if (input.value.trim() == "") {` - does the trick for me. – Jaza Aug 28 '15 at 00:59
  • I found these solutions have some bugs, original messages still poping up in some cases, for example when I double click select the text I entered and type some other text. In Firefox and Chrome. Although oninput should handle this it is not working for some reason. – pera Jun 27 '16 at 14:24
  • This is great, thanks for the snippet. Could it be expanded to include 'empty' messages for unchecked checkboxes? – matt_50 Jul 09 '17 at 12:18
  • In firefox (54) on completing a valid email address in an , this script causes a message bubble to display "undefined" and the form cannot be submitted. – matt_50 Jul 09 '17 at 13:07
  • Good start. The helper makes the assumption though that all inputs are required. Would be good to have it check for presence of `required` instead. Also it looks to me like this will only work for text-type inputs, no e.g. radio button groups, etc. – Madbreaks Feb 06 '18 at 21:25
68

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

<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

Akshay Khale
  • 8,151
  • 8
  • 50
  • 58
  • 18
    lol, everyone throwing out pages of code, i am so lazy and i was looking for inline one, thanks @akshay khale your answer is best one. – Dheeraj Thedijje Sep 17 '15 at 10:37
  • 1
    Happy to help @Thedijje – Akshay Khale Sep 20 '15 at 13:31
  • 16
    Please keep in mind that setCustomValidity has to be reset with something like `oninput="setCustomValidity('')"`: http://stackoverflow.com/a/16878766/1729850 – Leia Mar 10 '16 at 22:39
  • 1
    +1 to "Thedijje", I been searching for a simple solution like this. A lot of people out there is giving a lot of code, even mozilla developers give you a lot of code. It woul be awesome if the guides people make start with a simple example like this. – lcjury Oct 21 '16 at 13:20
  • 3
    Thanks @Leia for completing this answer. Unfortunately does not work for radio buttons. i.e if you trigger the invalid on one button, the custom string is added. Then if you click a different radio button, it will not clear the cutomValidity string on the first one. So looks like some javascript would be needed to listen and clear any setCustomValidity over all related radio buttons. – ryan2johnson9 Nov 11 '16 at 01:14
  • 1
    Following on from above.. instead of adding onclick(instead of oninput for radio) into the el for radio buttons I added a listener in js which resets it for all related radio buttons: `$('document').ready(function(){ $('input[type="radio"]').click(function(){ $('input[name="'+$(this).attr('name')+'"]').each(function(){ this.setCustomValidity("") }); }); });` – ryan2johnson9 Nov 11 '16 at 01:29
  • 1
    simply & super powerful! – xgqfrms Dec 20 '16 at 10:02
  • 2
    This should be the accepted answer. Simplicity is the best solution. – Keno Apr 23 '18 at 15:48
  • 1
    @AkshayKhale no need to - tested in various patterns and it's works! – gonatee Nov 28 '19 at 07:18
22

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/

Rikin Patel
  • 8,848
  • 7
  • 70
  • 78
16

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.

Levi Botelho
  • 24,626
  • 5
  • 61
  • 96
  • 1
    Any chance to use rich HTML content? It seems to support only text, no tags, such as `Error: Incorrect email address`. – Ωmega May 20 '13 at 12:29
  • As far as I know it isn't yet possible. You can style the result accordingly with CSS, but that of course has its limits and doesn't apply to your case. At any rate, the technology is still fairly new and not widely-supported enough for most, so whatever your implementation in my opinion you are still better off using an alternative solution for the time being. – Levi Botelho May 20 '13 at 13:16
  • Let's say sometimes (depends on other inputs), I want to allow empty value of such input field. How can I turn off default validation message then? Assigning `setCustomValidity("")` does not help. Is there some other parameter that needs to be set? Please advise. – Ωmega May 20 '13 at 13:58
8

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

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.

This is the field validation JavaScript code with jQuery:

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

<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 requiredmessage is 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 testing@.com! haha)

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

$("#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.

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
  • 1
    To avoid the non-standard attribute, you could use the standard `data-` prefix; e.g. `data-requiredMessage`. With jQuery, this is accessible with `$(element).data('requiredMessage')`; I don't know the standard DOM interface off the top of my head. – IMSoP Feb 10 '15 at 20:33
  • @IMSoP sure, it is valid! – DontVoteMeDown Feb 11 '15 at 10:16
6

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

davidcondrey
  • 34,416
  • 17
  • 114
  • 136
5

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!

Mimo
  • 6,015
  • 6
  • 36
  • 46
5

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

Example

var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');
LuisRBarreras
  • 61
  • 1
  • 2
5

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

eduardo a
  • 152
  • 4
  • 17
3

you can just simply using the oninvalid=" attribute, with the bingding the this.setCustomValidity() 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>

reference link

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

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

xgqfrms
  • 10,077
  • 1
  • 69
  • 68
1

You can add this script for showing your own message.

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

For other validation like pattern mismatch you can add addtional if else condition

like

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

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

Engineer
  • 300
  • 1
  • 9
0

use it on the onvalid attribute as follows

oninvalid="this.setCustomValidity('Special Characters are not allowed')
Aruna Prabhath
  • 206
  • 2
  • 10