Change the default HTML5 validation message language [duplicate] - html

I am trying to change the language of the error message in the html5 form field.
I have this code:
<input type="text" name="company_name" oninvalid="setCustomValidity('Lütfen işaretli yerleri doldurunuz')" required />
but on submit, even the field is not blank, I still get the error message.
I tried with <input type="text" name="company_name" setCustomValidity('Lütfen işaretli yerleri doldurunuz') required />
but then the english message is displayed. Anyone know how can I display the error message on other language?
Regards,Zoran

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" />
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.

your forget this in oninvalid, change your code with this:
oninvalid="this.setCustomValidity('Lütfen işaretli yerleri doldurunuz')"
<form><input type="text" name="company_name" oninvalid="this.setCustomValidity('Lütfen işaretli yerleri doldurunuz')" required /><input type="submit">
</form>

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('Lütfen işaretli yerleri doldurunuz');
}
else if (textbox.validity.typeMismatch){
textbox.setCustomValidity('Lütfen işaretli yere geçerli bir email adresi yazınız.');
}
else {
textbox.setCustomValidity('');
}
return true;
}
Demo :
http://jsfiddle.net/patelriki13/Sqq8e/4

This work for me.
<input oninvalid="this.setCustomValidity('custom text on invalid')" onchange="this.setCustomValidity('')" required>
onchange is a must!

I know this is an old post but i want to share my experience.
HTML:
<input type="text" placeholder="Username or E-Mail" required data-required-message="E-Mail or Username is Required!">
Javascript (jQuery):
$('input[required]').on('invalid', function() {
this.setCustomValidity($(this).data("required-message"));
});
This is a very simple sample. I hope this can help to anyone.

TLDR: Usually, you don't need to change the validation message but if you do use this:
<input
oninvalid="this.setCustomValidity('Your custom message / 您的自定义信息')"
oninput="this.setCustomValidity('')"
required="required"
type="text"
name="text"
>
The validation messages are coming from your browser and if your browser is in English the message will be in English, if the browser is in French the message will be in French and so on.
If you an input for which the default validation messages doesn't work for you, the easiest solution is to provide your custom message to setCustomValidity as a parameter.
...
oninvalid="this.setCustomValidity('Your custom message / 您的自定义信息')"
...
This is a native input's method which overwrites the default message. But now we have one problem, once the validation is triggered, the message will keep showing while the user is typing. So to stop the message from showing you can set the validity message to empty string using the oninput attribute.
...
oninput="this.setCustomValidity('')"
...

//Dynamic custome validation on all fields
//add validate-msg attr to all inputs
//add this js code
$("form :input").each(function(){
var input = $(this);
var msg = input.attr('validate-msg');
input.on('change invalid input', function(){
input[0].setCustomValidity('');
if(!(input[0].validity.tooLong || input[0].validity.tooShort)){
if (! input[0].validity.valid) {
input[0].setCustomValidity(msg);
}
}
});
});

<input type="text" id="inputName" placeholder="Enter name" required oninvalid="this.setCustomValidity('Your Message')" oninput="this.setCustomValidity('') />
this can help you even more better, Fast, Convenient & Easiest.

For the lost souls who are seeking a way to fully localize their error messages, see the snippet below. In short, you have to switch over the properties of event.target.validity and override the corresponding error message using event.target.setCustomValidity(message). If you just care about the empty field case as OP, just consider the case of valueMissing.
Note that the handler is passed in the React way, but other answers already covered how to do it in vanilla JS.
For the meaning of each validity state and how to implement customized error messages, see MDN: Validating forms using JavaScript.
const handleInvalidForm = (event) => {
const { patternMismatch,
tooLong,
tooShort,
rangeOverflow,
rangeUnderflow,
typeMismatch,
valid,
valueMissing } = event.target.validity;
if (patternMismatch)
event.target.setCustomValidity('...');
else if (tooLong)
event.target.setCustomValidity('...');
else if (tooShort)
event.target.setCustomValidity('...');
else if (rangeOverflow)
event.target.setCustomValidity('...');
else if (rangeUnderflow)
event.target.setCustomValidity('...');
else if (typeMismatch)
event.target.setCustomValidity('...');
else if (valid)
event.target.setCustomValidity('...');
else if (valueMissing)
event.target.setCustomValidity('...');
}
// ...
<form onSubmit={handleFormSubmit}
onInvalid={handleInvalidForm}
>
{emailTextField}
{passwordTextField}
{signInButton}
</form>

<input type="text" id="inputName" placeholder="Enter name" required oninvalid="this.setCustomValidity('Please Enter your first name')" >
this can help you even more better, Fast, Convenient & Easiest.

Do it using JS. Grab the class of the error message, and change it's content for whereever it appears.
var myClasses = document.getElementsByClassName("wpcf7-not-valid-tip");
for (var i = 0; i < myClasses.length; i++) {
myClasses[i].innerHTML = "Bitte füllen Sie das Pflichtfeld aus.";
}

<form>
<input
type="text"
name="company_name"
oninvalid="this.setCustomValidity('Lütfen işaretli yerleri doldurunuz')"
required
/><input type="submit" />
</form>

Related

validate input text with angularJS

I've got a form which adds items in my todo list array.
However if the input field is empty, my function is adding an empty value to my array.
What is the best way to validate the form?
<form name="formaddtodo" ng-submit="todoList.addTodo()">
<input type="text" ng-model="todoList.todoText" ng-minlength="1" size="30"
placeholder="Voeg nieuwe todo toe">
<input class="btn-primary" type="submit" value="voeg toe">
</form>
Here is my function
todoList.addTodo = function() {
todoList.todos.push({text:todoList.todoText, done:false});
todoList.todoText = '';
};
There is no validation yet but I'm curious what the best way is to validate.
Thank you in advance!
You can use the built-in ngRequired directive:
<input type="text" ng-model="todoList.todoText" ng-minlength="1" size="30"
placeholder="Voeg nieuwe todo toe" ng-required="required">
AngularJS provides basic implementation for most common HTML5 input
types: (text, number, url, email, date, radio, checkbox), as well as
some directives for validation (required, pattern, minlength,
maxlength, min, max).
https://docs.angularjs.org/guide/forms
<form name="formaddtodo" ng-submit="todoList.addTodo(formaddtodo.$valid)">
<input type="text" ng-model="todoList.todoText" ng-minlength="1" size="30"
placeholder="Voeg nieuwe todo toe" required>
<input class="btn-primary" type="submit" value="voeg toe">
</form>
todoList.addTodo = function(isValid) {
if(isValid) {
todoList.todos.push({text:todoList.todoText, done:false});
todoList.todoText = '';
}
};
I think the above code will help you to validate your form.
ngMessages module support for displaying messages to the user for form validation.
ngMessages, developers were forced to rely on directives such as ng-class and ng-show to display these errors.
Please follow this link. It might be useful for you now and in future use for validation with AngulerJS.

HTML form submits an empty string when JavaScript indicates the hidden control has a value

Amongst many other controls, I have the following HTML elements on a form
<input ID='cmdRegisterMe' name='cmdRegisterMe' value='Register Me' onclick="return preSubmit();" type='submit' />
<input type="hidden" ID="NewHash" name="NewHash" value="">
<INPUT TYPE="TEXT" ID="email" NAME="email" VALUE="" SIZE="50" MAXLENGTH="50">
<INPUT TYPE="PASSWORD" ID="password1" NAME="password1" VALUE="" SIZE="30" MAXLENGTH="25">
<INPUT TYPE="PASSWORD" ID="password2" NAME="password2" VALUE="" SIZE="30" MAXLENGTH="25">
and JS functions
function preSubmit() {
document.getElementById("NewHash").value = doNewHash(document.getElementById("password1").value, document.getElementById("email").value.toLowerCase());
alert(document.getElementById("NewHash").value);
document.getElementById("password1").value = '';
document.getElementById("password2").value = '';
return true;
}
function doNewHash(pw, strUsername) {
var hash_padding = '************';
return SHA1(SHA1(pw) + hash_padding + strUsername);
}
When I click Submit, I see the expected hashed value displayed by the call of alert().
However, in my PHP, the value of $_POST['NewHash'] is an empty string. I cannot fathom why this happens. In my understanding, there is no other code executed after the onclick() function returns true. I have done a global search on my code for 'NewHash' and there are no other assignments to it.
If I replace this line
document.getElementById("password1").value = '';
with this
document.getElementById("password1").value = document.getElementById("NewHash").value;
and inspect $_POST['password1'], it contains the hash value. What on earth could be happening to wipe out the value of 'NewHash'?
I have found what was wrong, but I hope posting the question may help someone else. I saved the PHP-generated HTML as a file, added to the top, and resolved to remove code piece by piece and submit until the submitted value for NewHash was no longer empty. I found I had TWO hidden controls called NewHash - so JS was displaying the value in one, and the browser was submitting the other!

An invalid form control with name='' is not focusable. WITHOUT ANY REQUIRED OR HIDDEN INPUTS

I'm facing the well known Chrome's "not-focusable-input" error but my situation is different from the explained in the other post I could find there.
I have this error message duplicated first on a well pointed input, this input has no required attribute:
The code:
<fieldset>
<label>Total (montaje incl.)</label>
<input type="number" id="priceFinal" name="priceFinal"> €
</fieldset>
The error:
An invalid form control with name='priceFinal' is not focusable.
While the user is filling the form this field gets its value by a js script with jquery. The user type a size in another input, the script do its maths with the size value and then put the outcome in the 'priceFinal' input with the jquery function: .val()
In the browser we can see that the input is correctly filled and no errors are displayed at that time. And with the 'novalidate' solution everything goes fine, so it couldn't be responsible for the nofocusable error, I think.
Then I got the same error with an input with no name which I didn't write and doesn't exist in my DOM:
An invalid form control with name='' is not focusable.
This is weird because the only input without name in my form is the type:submit one
<input type="submit" class="btn btn-default" value="Ver presupuesto" />
I have a few required fields but I've always checked that their are all filled when I send the form. I paste it just in case it could help:
<fieldset>
<input type="text" id="clientName" name="clientName" placeholder="Nombre y apellidos" class="cInput" required >
<input type="text" id="client_ID" name="client_ID" required placeholder="CIF / NIF / DNI" class="cInput">
</fieldset>
<fieldset>
<input type="text" id="client_add" name="client_add" placeholder="Dirección de facturación" class="addInput" required >
</fieldset>
<fieldset>
<input type="text" id="client_ph" name="client_ph" placeholder="Teléfono" class="cInput" required>
<input type="email" id="client_mail" name="client_mail" placeholder="Email" class="cInput" required>
</fieldset>
The novalidate solution clears the error but it doesn't fix it, I mean there must be a way to solve it with no hacks.
Any one have any idea of what's might going on?
Thanks
I had the same problem, and everyone was blaming to the poor hidden inputs been required, but seems like a bug having your required field inside a fieldset.
Chrome tries to focus (for some unknown reason) your fieldset instead of your required input.
This bug is present only in chrome I tested in version 43.0.2357.124 m.
Doesn't happen in firefox.
Example (very simple).
<form>
<fieldset name="mybug">
<select required="required" name="hola">
<option value=''>option 1</option>
</select>
<input type="submit" name="submit" value="send" />
</fieldset>
</form>
An invalid form control with name='mybug' is not focusable.
The bug is hard to spot because usually fieldsets don't have a name so name='' is a WTF! but slice piece by piece the form until I found the culprid.
If you get your required input from the fieldset the error is gone.
<form>
<select required="required" name="hola">
<option value=''>option 1</option>
</select>
<fieldset name="mybug">
<input type="submit" name="submit" value="send" />
</fieldset>
</form>
I would report it but I don't know where is the chrome community for bugs.
Thanks to this post, I saw that my problem also rested with Chrome trying to focus on my fieldsets, instead of the input field.
To get a better response from the console:
Assign every DOM element a new name
Set every input & select style.display to 'block'
Changed the type of input[type="hidden"] elements to 'text'
function cleanInputs(){
var inputs = document.getElementsByTagName( 'input' ),
selects = document.getElementsByTagName( 'select' ),
all = document.getElementsByTagName( '*' );
for( var i=0, x=all.length; i<x; i++ ){
all[i].setAttribute( 'name', i + '_test' );
}
for( var i=0, x=selects.length; i<x; i++ ){
selects[i].style.display = 'block';
}
for( var i=0, x=inputs.length; i<x; i++ ){
if( inputs[i].getAttribute( 'type' ) === 'hidden' ){
inputs[i].setAttribute( 'type', 'text' );
}
inputs[i].style.display = 'block';
}
return true;
}
In the console, I ran cleanInputs() and then submitted the form.
The result, from the console, was:
An invalid form control with name='28_test' is not focusable.
An invalid form control with name='103_test' is not focusable.
Then, switching over to the Web Developer "Elements" view, I was able to find "28_test" and "103_test" (both fieldsets) -- confirming that my problem was a required input field, nested inside a fieldset.
While I was writting the question I realized one thing: the value the script was putting into the 'priceFinal' field sometimes was a decimal number.
In this case the solution was to write the step attribute for this input:
... step="any" ...
Step on w3s
So this 'nofocusable' bug is not only a required and hidden fields issue, it's also generated by format conflicts.
Nach gave me the best pointer... (y) I also had a input type="number" with step="0.1" and the console shows me this error while validating: An invalid form control with name='' is not focusable.
remove the step="0.1" on the element and now the form can be validated
I had the same issue so I removed required="required" from the troublesome fields.
If you get the error when jQuery function is executed, try to put "return false" on your function, or function(e) { e.preventDefault(); ... }
i had this issue once. to fix it, add
novalidate
as an attribute to the form. e.g
<form action="" novalidate>
....
</form>
In my case, the input element did not have a required attribute but it was hidden. and the problem was while it was hidden, it had a value in it. I guess if an input field is hidden it shouldn't have a value too, aside required attribute.
When I remove the value through my javascript code, everything works fine.
Element is hidden, No required Attribute, No value. Worked
Here is the solution....
<form>
<input type="text" ng-show="displayCondition" ng-required="displayCondition"/>
</form>
Many people do not realize that passing false into ng-required disables the directive.

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

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"
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>
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:
the input looks like this:
<input type="text" title="Number with max 3 decimals" pattern="^\d+(\.\d{1,3})?$">
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.
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">
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.');
}
}
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>

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

For example I have a textfield. The field is mandatory, only numbers are required and length of value must be 10. When I try to submit form with value which length is 5, the default error message appears: Please match the requested format
<input type="text" required="" pattern="[0-9]{10}" value="">
How can I change HTML form validation errors default messages?
If the 1st point can be done, is there a way to create some property files and set in that files custom 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="" />
When using pattern= it will display whatever you put in the title attrib, so no JS required just do:
<input type="text" required="" pattern="[0-9]{10}" value="" title="This is an error message" />
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Plz enter on Alphabets ')" />
I found this code in another post.
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
To prevent the browser validation message from appearing in your document, with jQuery:
$('input, select, textarea').on("invalid", function(e) {
e.preventDefault();
});
you can remove this alert by doing following:
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity(' ')"
/>
just set the custom message to one blank space
you can change them via constraint validation api: http://www.w3.org/TR/html5/constraints.html#dom-cva-setcustomvalidity
if you want an easy solution, you can rock out civem.js, Custom Input Validation Error Messages JavaScript lib
download here: https://github.com/javanto/civem.js
live demo here: http://jsfiddle.net/hleinone/njSbH/
The setCustomValidity let you change the default validation message.Here is a simple exmaple of how to use it.
var age = document.getElementById('age');
age.form.onsubmit = function () {
age.setCustomValidity("This is not a valid age.");
};
I Found a way Accidentally Now:
you can need use this: data-error:""
<input type="username" class="form-control" name="username" value=""
placeholder="the least 4 character"
data-minlength="4" data-minlength-error="the least 4 character"
data-error="This is a custom Errot Text fot patern and fill blank"
max-length="15" pattern="[A-Za-z0-9]{4,}"
title="4~15 character" required/>
I found a bug on Mahoor13 answer, it's not working in loop so I've fixed it with this correction:
HTML:
<input type="email" id="eid" name="email_field" oninput="check(this)">
Javascript:
function check(input) {
if(input.validity.typeMismatch){
input.setCustomValidity("Dude '" + input.value + "' is not a valid email. Enter something nice!!");
}
else {
input.setCustomValidity("");
}
}
It will perfectly running in loop.
This is work for me in Chrome
<input type="text" name="product_title" class="form-control"
required placeholder="Product Name" value="" pattern="([A-z0-9À-ž\s]){2,}"
oninvalid="setCustomValidity('Please enter on Producut Name at least 2 characters long')" />
To set custom error message for HTML validation use,
oninvalid="this.setCustomValidity('Your custom message goes here.')"
and to remove this message when user enters valid data use,
onkeyup="setCustomValidity('')"
As you can see here:
html5 oninvalid doesn't work after fixed the input field
Is good to you put in that way, for when you fix the error disapear the warning message.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')" />