Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a custom message when an HTML5 required input pattern does not pass?

Tags:

html

People also ask

How do I bypass HTML5 validation?

To ignore HTML validation, you can remove the attribute on button click using JavaScript. Uer removeAttribute() to remove an attribute from each of the matched elements.

How do you show required messages in HTML?

The required attribute is a boolean attribute. When present, it specifies that an input field must be filled out before submitting the form. Note: The required attribute works with the following input types: text, search, url, tel, email, password, date pickers, number, checkbox, radio, and file.

How do I create a custom validation in HTML?

The setCustomValidity method allows you to set a custom text by changeing the validationMessage property of the DOM node that contains the message. When the input is checked by checkValidity method on a form element node, and found to be invalid, the invalid event is fired for the node.


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>

http://jsfiddle.net/44wSU/1/


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/


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')"/>

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