Set Custom Html5 Required Field Validation Message

HTML5 form required attribute. Set custom validation message?

Use setCustomValidity:

document.addEventListener("DOMContentLoaded", function() {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("This field cannot be left blank");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})

I changed to vanilla JavaScript from Mootools as suggested by @itpastorn in the comments, but you should be able to work out the Mootools equivalent if necessary.

Edit

I've updated the code here as setCustomValidity works slightly differently to what I understood when I originally answered. If setCustomValidity is set to anything other than the empty string it will cause the field to be considered invalid; therefore you must clear it before testing validity, you can't just set it and forget.

Further edit

As pointed out in @thomasvdb's comment below, you need to clear the custom validity in some event outside of invalid otherwise there may be an extra pass through the oninvalid handler to clear it.

Set custom HTML5 required field validation message

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

HTML5 Input Validation with Custom Message

You could use the oninput attribute to restore the validity of the form like this: oninput="setCustomValidity('')".

This has a side effect and it is that if you type an invalid input and submit the form and type again another invalid value immediately the default message is shown instead of the custom one until you click again the submit option.

(See this forked jsfiddle, or below working snippet)

<form>  <input type="text" pattern=".{3,}" placeholder="min 3">  <input type="text" placeholder="min 4" pattern=".{4,}" oninvalid="setCustomValidity('Must be 4 Characters')" oninput="setCustomValidity('')">  <input type="submit" value="Check" /></form>

How set time for validation message on HTML5 form required attribute?

The UI is implemented by the browser and isn't customisable. Different browsers will implement it differently. (e.g. when I test it, the message is displayed until I interact with the page again).

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

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/

How to change the default message of the required field in the popover of form-control in bootstrap?

You can use setCustomValidity function when oninvalid event occurs.

Like below:-

<input class="form-control" type="email" required="" 
placeholder="username" oninvalid="this.setCustomValidity('Please Enter valid email')">
</input>

Update:-

To clear the message once you start entering use oninput="setCustomValidity('') attribute to clear the message.

<input class="form-control" type="email"  required="" placeholder="username"
oninvalid="this.setCustomValidity('Please Enter valid email')"
oninput="setCustomValidity('')"></input>

changing the language of error message in required field in html5 contact form

setCustomValidity's purpose is not just to set the validation message, it itself marks the field as invalid. It allows you to write custom validation checks which aren't natively supported.

You have two possible ways to set a custom message, an easy one that does not involve Javascript and one that does.

The easiest way is to simply use the title attribute on the input element - its content is displayed together with the standard browser message.

<input type="text" required title="Lütfen işaretli yerleri doldurunuz" />

Sample Image

If you want only your custom message to be displayed, a bit of Javascript is required. I have provided both examples for you in this fiddle.

HTML5 Validation: different behavior when custom validation message is set

The problem was solved by changing 'onchange' to 'oninput' and have a custom function handle the setCustomValidity correctly, like in this answer to another question by Rikin Patel:

HTML:

<input type="text" pattern="[0-9]{10}" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" />

JAVASCRIPT :

function InvalidMsg(textbox) {

if(textbox.validity.patternMismatch){
textbox.setCustomValidity('please enter 10 numeric value.');
}
else {
textbox.setCustomValidity('');
}
return true;
}

Fiddle Demo

HTML 5 validation error display onblur of the field instead of onsubmit

Simpliy add onblur="this.reportValidity()" to your form element.

<input type="text" onblur="this.reportValidity()" name="mobile" ... required id="id_mobile" >

Custom HTML5 form validation not showing custom error initially

After setting the validity message, you need to call element.reportValidity() to make it show up.

setCustomValidity(message)

Sets a custom error message string to be shown to the user upon submitting the form, explaining why the value is not valid — when a message is set, the validity state is set to invalid. To clear this state, invoke the function with an empty string passed as its argument. In this case the custom error message is cleared, the element is considered valid, and no message is shown.

reportValidity()

Checks the element's value against its constraints and also reports the validity status; if the value is invalid, it fires an invalid event at the element, returns false, and then reports the validity status to the user in whatever way the user agent has available. Otherwise, it returns true.

You also need to use event.preventDefault() on the form submission event whenever the input is invalid, so that the form submission doesn't go through.

Here is an example: