I am trying to change the default error message "setCustomValidity" throws on email being invalid.
I cannot access the source code. My assumption is that the source somehow invokes setCustomValidity; just because of the look of the error message. This is the source element:
<input type="email" value="" name="customer[email]" id="email" class="large" size="30">
I can only inject any change using external JavaScript/css file.
I could think of two solutions.
Solution 1: I am trying to inject inline HTML element using JS which would result in something like this.
<input type="email" value="" name="customer[email]" class="large" size="30" oninvalid="this.setCustomValidity('Please Enter valid email')" oninput="setCustomValidity('')">
I am new to JS and I am having a hard time figuring how to implement HTML in an external JS file.
Solution 2: Invoke the oninvalid and setCustomValidity DOM methods in error_message.js like so:
function emailValidity(){
var myInput = document.getElementByName("customer[email]");
myInput.oninvalid = function() {
(errorMessage)
};
function errorMessage(){
myInput.setCustomValidity("hey! the email isn't right");
}
}
But this file even after being included somehow fails to override the default message!
Any help is appreciated. Thank you in advance.
Additionally you must call the reportValidity method on the same element or nothing will happen.
HTMLObjectElement.setCustomValidity
function validate(input) {
var validityState_object = input.validity;
console.log(validityState_object)
if (validityState_object.typeMismatch) {
input.setCustomValidity('Thats not an email!');
input.reportValidity();
} else {
input.setCustomValidity('');
input.reportValidity();
}
}
document.querySelector('#email').addEventListener('blur', e =>
validate(e.target)
)
<input type="email" value="" id="email">
Just set the input and invalid event listeners in much the same way.
const input = document.querySelector('input');
input.oninput = () => input.setCustomValidity('');
input.oninvalid = () => input.setCustomValidity('Please Enter valid email');
<form>
<input type="email" value="" name="customer[email]" class="large" size="30">
</form>
Your code wasn't working because it wasn't in a form. A form needs a submit button to check the inputs and display an error message if necessary, so I added that.
Also, you have getElementByName when it should be getElementsByName, with a later on [0] indexing to select the element.
In addition to that, you were trying to set the validity every time the user tried to submit, when it only needed to be set once.
Try this:
var myInput = document.getElementsByName("customer[email]")[0];
myInput.oninvalid = function() {
myInput.setCustomValidity("Hey! the email isn't right")
};
<form>
<input type="email" name="customer[email]" id="email" class="large" size="30">
<input type="submit" onsubmit="emailValidity()">
</form>
This is how I solved it:
customAnswer.js
document.addEventListener("DOMContentLoaded", function(event) {
// Source text: "Fill out this field."
var validateElements1 = document.querySelectorAll('input#username, input#password');
if (validateElements1.length > 0) {
for (var x = 0; x < validateElements1.length; x++) {
validateElements1[x].setAttribute("oninvalid","this.setCustomValidity('Complete este campo.')");
validateElements1[x].setAttribute("oninput","this.setCustomValidity('')");
}
}
});
This question already has answers here:
Show/hide element without inline Javascript
(2 answers)
Closed 3 years ago.
I have same input class,type in several pages like the following :
<input type="text" name="studentID" id="studentID" class="form-control student-id"/>
what I want using the same class name student-id ,
it will validate student id using the following js :
function validateStudentId(){
var studentId= document.getElementsByClassName('student-id');
if (studentId.length > 0) {
var id = studentId[0].value;
console.log('lengthe'+id.length);
if(id.length > 7){
alert('Please enter valid student id .');
$('.student-id').val("");
return;
}
if(isNaN(id)){
alert('Entered input is not a number .');
$('.student-id').val("");
return;
}
}
}
To do this job I've already done the following :
<input type="text" class="form-control student-id" onchange="validateStudentId()" name="studentid" size="10" maxlength="7" />
An onchange function added. Is there any better way to do this.
coz I have to do this onchange function call every time.
So what I want is to give only class name and it will automatically validate the field using the class name.
Suggest me any better idea, Just dont want to write onchange function every time ??
Thanks
You can use document.querySelectorAll('input.student-id') to select all inputs with that class and then .forEach() on the node list to iterate over them and call the validation function on each of them.
I also replaced the jQuery calls with plain JavaScript because it's really simple for this use case. I switched the check for a numeric value to come before the length check as well, because that seems more logical to me.
function validateStudentId(inputEl) {
var studentId = inputEl;
var id = studentId.value;
console.log('length: ' + id.length);
if (isNaN(id)) {
alert('Entered input is not a number .');
inputEl.value = "";
return;
}
if (id.length > 7) {
alert('Please enter valid student id .');
inputEl.value = "";
return;
}
}
document.querySelectorAll('input.student-id').forEach(function(inputEl) {
inputEl.addEventListener('change', function() {
validateStudentId(this);
});
});
<input type="text" name="studentID" id="studentID" class="form-control student-id" value="abc" />
<input type="text" name="studentID2" id="studentID2" class="form-control student-id" value="1234567890" />
<input type="text" name="studentID3" id="studentID3" class="form-control student-id" value="123456" />
my simple html file code
Site Name: <input id="name" type="text" onkeyup="myFunction1(event,this)">
URL : <input id="url" type="text">
javascript code
function myFunction1(event,t){
var nameval= document.getElementById("name").value;
var urlval= document.getElementById("url").value;
var namelen = nameval.length;
var urllen = urlval.length;
var res = nameval.substring(1, namelen);
if(res.length == urllen){
document.getElementById("url").value = t.value;
}
else{
alert("string lengths are not matching");
}
}
what i want to do when user type Site Name in textbox, same text should reflect to URL textbox if name and url text boxes have same text lenghts . but when i speed type site name, my if condition fail after typing few characters and it goes to else block. i dont know why this happening. can anyone help me to improve this code?
Using the onkeyup event isn't your best option for what you are trying to do. You can use the oninput event instead. Here's the modified HTML:
Site Name: <input id="name" type="text" oninput="myFunction1(event,this)">
URL : <input id="url" type="text">
So my question is, how do I pass variables to javascript functions through html input boxes?
Like, let's say I have a function:
function Call(number, text, callerID, CallerIDName, PassCode)
How would I make an input box in html so that when the user submits a value into the box, it would set the variable for that corresponding box?
All help is appreciated, thanks!
Try something like this...
Name: <input type="text" id="number"><br>
Text: <input type="text" id="text"><br>
Caller Id Name: <input type="text" id="CallerIDName"><br>
Passcode: <input type="text" id="Passcode"><br>
<script>
function Call() {
var number = document.getElementById("number").value;
var text = document.getElementById("text").value;
var CallerIDName = document.getElementById("CallerIDName").value;
var Passcode = document.getElementById("Passcode").value;
//do something here...
}
</script>
<button onclick="Call();">Click to Call</button>
Let's say you have an input tag for the "number" parameter:
<input type="text" id="number" />
You can then obtain the value of the field like this;
document.getElementById("number").value
You can find a few examples here. Let me know if I misunderstood your question.
I've got the following HTML form: http://jsfiddle.net/nfgfP/
<form id="form" onsubmit="return(login())">
<input name="username" placeholder="Username" required />
<input name="pass" type="password" placeholder="Password" required/>
<br/>Remember me: <input type="checkbox" name="remember" value="true" /><br/>
<input type="submit" name="submit" value="Log In"/>
Currently when I hit enter when they're both blank, a popup box appears saying "Please fill out this field". How would I change that default message to "This field cannot be left blank"?
The type password field's error message is simply *****. To recreate this give the username a value and hit submit.
Here is some code to display a custom error message:
<input type="text" id="username" required placeholder="Enter Name"
oninvalid="ths.setCustomValidity('Enter User Name Here')"
oninput="setCustomValidity('')"/>
This part is important because it hides the error message when the user inputs new data:
oninput="setCustomValidity('')"
Note: the this keyword is not required for inline event handlers, but you may want to use it anyway for consistency.
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.
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.
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.
It's very simple to control custom messages with the help of HTML5 event oninvalid
Here is code:
<input id="UserID" type="text" required="required"
oninvalid="this.setCustomValidity('Witinnovation')"
onvalid="this.setCustomValidity('')">
This is most important:
onvalid="this.setCustomValidity('')"
Note: This no longer works in Chrome, not tested in other browsers. See edits below. This answer is being left here for historical reference.
If you feel that the validation string really should not be set by code, you can set you input element's title attribute to read "This field cannot be left blank". (Works in Chrome 10)
title="This field should not be left blank."
See http://jsfiddle.net/kaleb/nfgfP/8/
And in Firefox, you can add this attribute:
x-moz-errormessage="This field should not be left blank."
Edit
This seems to have changed since I originally wrote this answer. Now adding a title does not change the validity message, it just adds an addendum to the message. The fiddle above still applies.
Edit 2
Chrome now does nothing with the title attribute as of Chrome 51. I am not sure in which version this changed.
It's very simple to control custom messages with the help of the HTML5 oninvalid event
Here is the code:
User ID
<input id="UserID" type="text" required
oninvalid="this.setCustomValidity('User ID is a must')">
By setting and unsetting the setCustomValidity in the right time, the validation message will work flawlessly.
<input name="Username" required
oninvalid="this.setCustomValidity('Username cannot be empty.')"
onchange="this.setCustomValidity('')" type="text" />
I used onchange instead of oninput which is more general and occurs when the value is changed in any condition even through JavaScript.
I have made a small library to ease changing and translating the error messages. You can even change the texts by error type which is currently not available using title in Chrome or x-moz-errormessage in Firefox. Go check it out on GitHub, and give feedback.
It's used like:
<input type="email" required data-errormessage-value-missing="Please input something">
There's a demo available at jsFiddle.
Try this one, its better and tested:
function InvalidMsg(textbox) {
if (textbox.value === '') {
textbox.setCustomValidity('Required email address');
} else if (textbox.validity.typeMismatch){
textbox.setCustomValidity('please enter a valid email address');
} else {
textbox.setCustomValidity('');
}
return true;
}
<form id="myform">
<input id="email"
oninvalid="InvalidMsg(this);"
oninput="InvalidMsg(this);"
name="email"
type="email"
required="required" />
<input type="submit" />
</form>
Demo:
http://jsfiddle.net/patelriki13/Sqq8e/
The easiest and cleanest way I've found is to use a data attribute to store your custom error. Test the node for validity and handle the error by using some custom html.
le javascript
if(node.validity.patternMismatch)
{
message = node.dataset.patternError;
}
and some super HTML5
<input type="text" id="city" name="city" data-pattern-error="Please use only letters for your city." pattern="[A-z ']*" required>
The solution for preventing Google Chrome error messages on input each symbol:
<p>Click the 'Submit' button with empty input field and you will see the custom error message. Then put "-" sign in the same input field.</p>
<form method="post" action="#">
<label for="text_number_1">Here you will see browser's error validation message on input:</label><br>
<input id="test_number_1" type="number" min="0" required="true"
oninput="this.setCustomValidity('')"
oninvalid="this.setCustomValidity('This is my custom message.')"/>
<input type="submit"/>
</form>
<form method="post" action="#">
<p></p>
<label for="text_number_1">Here you will see no error messages on input:</label><br>
<input id="test_number_2" type="number" min="0" required="true"
oninput="(function(e){e.setCustomValidity(''); return !e.validity.valid && e.setCustomValidity(' ')})(this)"
oninvalid="this.setCustomValidity('This is my custom message.')"/>
<input type="submit"/>
</form>
I have a simpler vanilla js only solution:
For checkboxes:
document.getElementById("id").oninvalid = function () {
this.setCustomValidity(this.checked ? '' : 'My message');
};
For inputs:
document.getElementById("id").oninvalid = function () {
this.setCustomValidity(this.value ? '' : 'My message');
};
Okay, oninvalid works well but it shows error even if user entered valid data. So I have used below to tackle it, hope it will work for you as well,
oninvalid="this.setCustomValidity('Your custom message.')" onkeyup="setCustomValidity('')"
If your error message is a single one, then try below.
<input oninvalid="this.setCustomValidity('my error message')"
oninput="this.setCustomValidity('')"> <!-- 👈 don't forget it. -->
To handle multiple errors, try below
<input oninput="this.setCustomValidity('')">
<script>
inputElem.addEventListener("invalid", ()=>{
if (inputElem.validity.patternMismatch) {
return inputElem.setCustomValidity('my error message')
}
return inputElem.setCustomValidity('') // default message
})
</script>
Example
You can test valueMissing and valueMissing.
<form>
<input pattern="[^\\/:\x22*?<>|]+"
placeholder="input file name"
oninput="this.setCustomValidity('')"
required
>
<input type="submit">
</form>
<script>
const form = document.querySelector("form")
const inputElem = document.querySelector(`input`)
inputElem.addEventListener("invalid", ()=>{
if (inputElem.validity.patternMismatch) {
return inputElem.setCustomValidity('Illegal Filename Characters \\/:\x22?<>|')
}
return inputElem.setCustomValidity('') // return default message according inputElem.validity.{badInput, customError, tooLong, valueMissing ...}
})
form.onsubmit = () => {
return false
}
</script>
ValidityState
const username= document.querySelector('#username');
const submit=document.querySelector('#submit');
submit.addEventListener('click',()=>{
if(username.validity.typeMismatch){
username.setCustomValidity('Please enter User Name');
}else{
username.setCustomValidity('');
}
if(pass.validity.typeMismatch){
pass.setCustomValidity('Please enter Password');
}else{
pass.setCustomValidity('');
}
})
Adapting Salar's answer to JSX and React, I noticed that React Select doesn't behave just like an <input/> field regarding validation. Apparently, several workarounds are needed to show only the custom message and to keep it from showing at inconvenient times.
I've raised an issue here, if it helps anything. Here is a CodeSandbox with a working example, and the most important code there is reproduced here:
Hello.js
import React, { Component } from "react";
import SelectValid from "./SelectValid";
export default class Hello extends Component {
render() {
return (
<form>
<SelectValid placeholder="this one is optional" />
<SelectValid placeholder="this one is required" required />
<input
required
defaultValue="foo"
onChange={e => e.target.setCustomValidity("")}
onInvalid={e => e.target.setCustomValidity("foo")}
/>
<button>button</button>
</form>
);
}
}
SelectValid.js
import React, { Component } from "react";
import Select from "react-select";
import "react-select/dist/react-select.css";
export default class SelectValid extends Component {
render() {
this.required = !this.props.required
? false
: this.state && this.state.value ? false : true;
let inputProps = undefined;
let onInputChange = undefined;
if (this.props.required) {
inputProps = {
onInvalid: e => e.target.setCustomValidity(this.required ? "foo" : "")
};
onInputChange = value => {
this.selectComponent.input.input.setCustomValidity(
value
? ""
: this.required
? "foo"
: this.selectComponent.props.value ? "" : "foo"
);
return value;
};
}
return (
<Select
onChange={value => {
this.required = !this.props.required ? false : value ? false : true;
let state = this && this.state ? this.state : { value: null };
state.value = value;
this.setState(state);
if (this.props.onChange) {
this.props.onChange();
}
}}
value={this && this.state ? this.state.value : null}
options={[{ label: "yes", value: 1 }, { label: "no", value: 0 }]}
placeholder={this.props.placeholder}
required={this.required}
clearable
searchable
inputProps={inputProps}
ref={input => (this.selectComponent = input)}
onInputChange={onInputChange}
/>
);
}
}
For a totaly custom check logic:
$(document).ready(function() {
$('#form').on('submit', function(e) {
if ($('#customCheck').val() != 'apple') {
$('#customCheck')[0].setCustomValidity('Custom error here! "apple" is the magic word');
$('#customCheck')[0].reportValidity();
e.preventDefault();
}
});
$('#customCheck').on('input', function() {
$('#customCheck')[0].setCustomValidity('');
});
});
input {
display: block;
margin-top: 15px;
}
input[type="text"] {
min-width: 250px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form">
<input type="text" placeholder="dafault check with 'required' TAG" required/>
<input type="text" placeholder="custom check for word 'apple'" id="customCheck" />
<input type="submit">
</form>
Can be easily handled by just putting 'title' with the field:
<input type="text" id="username" required title="This field can not be empty" />