How to Change The Image Inside an HTML5 Form-Validation Message

How do I change the image inside an HTML5 form-validation message?

Try:

input::-webkit-validation-bubble-icon {
display: none;
}

or, of course:

input::-webkit-validation-bubble-icon {
background: url(http://google.com/favicon.ico);
}

Jsfiddle here: http://jsfiddle.net/xhqhV/

How can I change or remove HTML form validation default error messages?

This is the JavaScript solution:

 <input type="text"
pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Please enter Alphabets.')"
onchange="try{setCustomValidity('')}catch(e){}" />

The "onchange" event needs when you set an invalid input data, then correct the input and send the form again.
I've tested it on Firefox, Chrome and Safari.

But for Modern Browsers:

Modern browsers didn't need any JavaScript for validation.
Just do it like this:

<input type="text"
pattern="[a-zA-Z]+"
title="Please enter Alphabets."
required="" />

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

HTML Default validation messages styling

At this point the answer seems to be that you can't style the default validation boxes.

Please if anyone has links or a solution to this please add info.

I haven't been able to find anything on this.

If someone adds a viable solution I will accept your answer.

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.

Display validation message for radio buttons with images inline

Added three lines of code in your javascript validation to force show invalid feedback on no selection and add some styling on images

        // Example starter JavaScript for disabling form submissions if there are invalid fields        (function () {            'use strict';            window.addEventListener('load', function () {                // Fetch all the forms we want to apply custom Bootstrap validation styles to                var forms = document.getElementsByClassName('needs-validation');                // Loop over them and prevent submission                var validation = Array.prototype.filter.call(forms, function (form) {                    form.addEventListener('submit', function (event) {                        if (form.checkValidity() === false) {                            if ($('input.Check[name=mb]:checked').length < 1) {                                 $(".img-thumbnail").css('outline', '1px solid red');                               $(".invalid-feedback").show();            }                            event.preventDefault();                            event.stopPropagation();                        }                        form.classList.add('was-validated');                    }, false);                });            }, false);        })();
   img    {        height:100px;        width:100px;        object-fit: cover;      }  
<html>
<head> <meta name="viewport" content="initial-scale=1, width=device-width"> <!-- http://getbootstrap.com/docs/4.1/ --> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script> <title>snippet</title></head>
<body> <form action="#" class="needs-validation" novalidate> <div id="mb"> <input type="radio" id="h" value="hancock" name="mb" required> <label for="h"><img src="https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=format%2Ccompress&cs=tinysrgb&dpr=1&w=500" class="img-thumbnail" alt="h"></label> <input type="radio" id="s" value="shirahoshi" name="mb" required> <label for="s"><img src="https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=format%2Ccompress&cs=tinysrgb&dpr=1&w=500" class="img-thumbnail" alt="s"></label> <input type="radio" id="n" value="nami" name="mb" required> <label for="n"><img src="https://images.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg?auto=format%2Ccompress&cs=tinysrgb&dpr=1&w=500" class="img-thumbnail" alt="n"></label> <div class="invalid-feedback">Pick One!</div> </div> <button class="btn btn-primary" type="submit" style="margin-left:11px">Submit</button> </form> </body>
</html>

How can i change the default error message for extention of the jquery's validation plugin?

if extension is not matched it shows "Please enter a value with a valid mimetype."

Mimetype has nothing to do with file extension, therefore this cannot be the default message from the extension rule.

"enter valid mimetype" is the default error message from the accept rule, which validates mimetype, and that you have declared inline with your HTML markup here:

<input class="form-control" type="file" accept="image/png, image/gif, image/jpeg" name="fileToUpload" ....

This plugin is easier to use and understand when you declare all rules using one consistent method, rather than mixing inline HTML5 rules with your jQuery .validate() rules.

The jQuery Validate plugin automatically converts various inline declarations into rules, such as HTML5 and certain class names.

Example: Inline required="required" or class="required" will do the same thing as required: true inside rules option of .validate().

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/



Related Topics



Leave a reply



Submit