35

I have the following:

<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" />

When I enter just one character I get a message saying:

"Please match the requested format"

Is there a way I can customize this message to say something like "Please enter at least 5 characters"

  • Make sure the requirements are visible even if javascript is disabled. Maybe add it to the label for this input? – Sumurai8 Oct 01 '13 at 18:06
  • possible duplicate http://stackoverflow.com/questions/5272433/html5-form-required-attribute-set-custom-validation-message – kasper Taeymans Oct 01 '13 at 18:06

8 Answers8

26

You can do a quick and dirty way with this trick:

<form>  
 <label for="username">Username:</label><br/>
  <input id="username" type="text" pattern=".{6,}" autofocus required title="Please enter at least 5 characters">        
  <input id="submit" type="submit" value="create">   
</form>
trinalbadger587
  • 1,905
  • 1
  • 18
  • 36
OBV
  • 1,169
  • 1
  • 12
  • 25
  • if it encounter an error (like display message) then that error won't go away. – Athar Feb 26 '16 at 11:26
  • 1
    @Athar it goes away as soon as input becomes valid. – naXa stands with Ukraine Oct 19 '18 at 15:00
  • Thanks for the reply, yeah It should go away and I haven't tested this lately. – Athar Oct 22 '18 at 12:11
  • 4
    This answer that uses the `title` attribute, is idiomatically correct, with regard to HTML specification: https://html.spec.whatwg.org/multipage/input.html#attr-input-title, unlike the accepted solution that uses `setCustomValidity` inappropriately. – Armen Michaeli Sep 18 '19 at 09:10
  • 1
    Except note that the spec says " User agents **may** use the contents of this attribute, if it is present, when informing the user that the pattern is not matched", which is very different from "User agents _must_ use the [...]". In fact, no current desktop browser implements this permitted behaviour using the code from the JSFiddle (Chrome 81, FF 78, and Edge 18.18363) – Mike 'Pomax' Kamermans May 18 '20 at 18:01
23

Use: setCustomValidity

First function sets custom error message:

$(function(){
    $("input[name=Password]")[0].oninvalid = function () {
        this.setCustomValidity("Please enter at least 5 characters.");
    };
});

Second function turns off custom message. Without this function custom error message won't turn off as the default message would:

$(function(){
    $("input[name=Password]")[0].oninput= function () {
        this.setCustomValidity("");
    };
});

P.S. you can use oninput for all input types that have a text input.

For input type="checkbox" you can use onclick to trigger when error should turnoff:

$(function(){
    $("input[name=CheckBox]")[0].onclick= function () {
        this.setCustomValidity("");
    };
});

For input type="file" you should use change.

The rest of the code inside change function is to check whether the file input is not empty.

P.S. This empty file check is for one file only, feel free to use any file checking method you like as well as you can check whether the file type is to your likes.

Function for file input custom message handling:

$("input[name=File]").change(function () {
    let file = $("input[name=File]")[0].files[0];
    if(this.files.length){
        this.setCustomValidity("");
    }
    else {
        this.setCustomValidity("You forgot to add your file...");
    }
    //this is for people who would like to know how to check file type
    function FileType(filename) {
        return (/[.]/.exec(filename)) ? /[^.]+$/.exec(filename) : undefined;
    }
    if(FileType(file.name)!="pdf"||FileType(file.name)!="PDF"){
        this.setCustomValidity("Your file type has to be PDF");
    //this is for people who would like to check if file size meets requirements
    else if(file.size/1048576>2){
        // file.size divided by 1048576 makes file size units MB file.size to megabytes
        this.setCustomValidity("File hast to be less than 2MB");
    }
    else{
    this.setCustomValidity("");
    }
});//file input custom message handling function

HTML5 form required attribute. Set custom validation message?

JSFiddle: http://jsfiddle.net/yT3w3/

Non-JQuery solution:

function attachHandler(el, evtname, fn) {
    if (el.addEventListener) {
        el.addEventListener(evtname, fn.bind(el), false);
    } else if (el.attachEvent) {
        el.attachEvent('on' + evtname, fn.bind(el));
    }
}
attachHandler(window, "load", function(){
    var ele = document.querySelector("input[name=Password]");
     attachHandler(ele, "invalid", function () {
        this.setCustomValidity("Please enter at least 5 characters.");
        this.setCustomValidity("");
    });
});

JSFiddle: http://jsfiddle.net/yT3w3/2/

Yakuza
  • 23
  • 3
gp.
  • 8,074
  • 3
  • 38
  • 39
  • Should I place this at the top of the page? Also can you show me how I should call this. Do I need to have something surrounding this to make sure the page is ready? –  Oct 01 '13 at 18:18
  • The function block passed to $() is executed on page ready. So just copy the code in script tag anywhere and it would be fine. – gp. Oct 01 '13 at 18:29
  • I do this but I get the message: Uncaught ReferenceError: $ is not defined –  Oct 01 '13 at 18:40
  • you need to add jquery reference. – gp. Oct 01 '13 at 18:43
  • but I don't use jquery :-( –  Oct 02 '13 at 04:20
  • 1
    The answer is incorrect. `setCustomValidity` does not set custom validation message -- it sets custom validation condition! Meaning that it's for cases when the value of an input control matches specified pattern, yet the application still considers it invalid -- you then invoke `setCustomValidity` (as response to change of value) with the message you want to be displayed for the now invalid control. When the value changes to what application considers valid again, `setCustomValidity` should be called with an empty string. – Armen Michaeli Sep 18 '19 at 09:02
  • 1
    As the question explains, the person wants the application to alert user of a value that does *not* match the specified pattern, which is not a custom validity condition, it's a built-in check the user agent does anyway. The right way to help program the user agent to alert the user with a custom message in cases of value not matching the pattern (which is what is asked in the question) is [to use the `title` attribute](https://html.spec.whatwg.org/multipage/input.html#attr-input-title). – Armen Michaeli Sep 18 '19 at 09:07
22

I'd add another attribute oninvalid.

oninvalid="setCustomValidity('Please enter at least 5 characters')"

<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" oninvalid="setCustomValidity('Please enter at least 5 characters')"/>
  • 4
    This is only partially complete. It does not "clear" the error even once the pattern is matched. The correct answer is here: https://stackoverflow.com/a/30136146/870729 – random_user_name Jun 22 '17 at 21:06
  • 2
    This answer will not clear the error message and therefore will not allow the form to validate even if you correct the data. You need to also add `onchange="setCustomValidity('')"` to clear the message so the form can actually validate. – jsherk Jan 16 '20 at 07:33
11

I found that, chrome at least, adds to the message the title of the input automatically, so no extra js is required, see this:

enter image description here

the input looks like this:

<input type="text" title="Number with max 3 decimals" pattern="^\d+(\.\d{1,3})?$">
santiago arizti
  • 4,175
  • 3
  • 37
  • 50
6

It is very simple without javascript or jQuery validation. We can achieve it by HTML5

Let suppose we have HTML field:

<input required pattern=".{6,}" class="big medium-margin" name="Password" placeholder="Password" size="25" type="password" />

Just change the HTML as

<input required pattern=".{6,}" class="big medium-margin" title="Please enter at least 5 characters." name="Password" placeholder="Password" size="25" type="password" />

If you observe, just add title = "Error message"

Now whenever form will be post, the given messages will be appeared and we did not need JavaScript or jQuery check. This solution works for me.

rajausman haider
  • 570
  • 2
  • 10
  • 20
3

I simply use oninvalid to set the custom validty error message and then use onchange to reset the message so the form can submit.

<input type="number" oninvalid="this.setCustomValidity('Please enter an INTEGER')" onchange="this.setCustomValidity('')" name="integer-only" value="0" min="0" step="1">
jsherk
  • 6,128
  • 8
  • 51
  • 83
0

You'd need to use the setCustomValidity function. The problem with this is that it'd only guarantee a custom message for users who have JavaScript enabled.

<input required pattern=".{6,}" ... oninput="check(this)">
                                    ^^^^^^^^^^^^^^^^^^^^^

function check (input) {
    if (input.value.search(new RegExp(input.getAttribute('pattern'))) >= 0) {
        // Input is fine. Reset error message.
        input.setCustomValidity('');
    } else {
        input.setCustomValidity('Your custom message here.');
    }
}
federico-t
  • 12,014
  • 19
  • 67
  • 111
  • No, `setCustomValidity` isn't for this purpose. Please see me elaborate on this in a comment to other answers for the question. – Armen Michaeli Sep 18 '19 at 09:12
0

https://www.geeksforgeeks.org/form-required-attribute-with-a-custom-validation-message-in-html5/

    <input id="gfg" type="number" min="101" max="999" required> 

    <button onclick="myFunction()">Try it</button> 


    <p id="geeks"></p> 

    <script> 
        function myFunction() { 
            var inpObj = document.getElementById("gfg"); 
            if (!inpObj.checkValidity()) { 
                document.getElementById("geeks") 
                        .innerHTML = inpObj.validationMessage; 
            } else { 
                document.getElementById("geeks") 
                        .innerHTML = "Input is ALL RIGHT"; 
            } 
        } 
    </script>