Javascript validation nightmare - javascript

I'm trying to get my "username" and "password" fields to verify that there is information in them before submitting the form.
What should I need to add to my HTML and to my JavaScript to have them work! If you want to suggest a new JavaScript, please do!
HTML:
<form action="validateForm.html" id="registrationForm">
<label for="username" id="usernameLabel">* Username:</label>
<input type="text" name="username" id="username" value="Your username" />
<div id="usernameError" style="display:none"></div>
<br/><br/>
<label for="password" id="passwordLabel">* Password:</label>
<input type="password" name="password" id="password" />
<div id="passwordError" style="display:none"></div>
<br/><br/>
<input type="submit" value="Submit Form" id="submit" />
</form>
JavaScript
function validateForm()
{
if(!document.getElementByName("username"))
{
alert("Username field is required!");
}
if(!document.forms[0].username){
alert("Username field is required!");
}
if(!document.for (var i = username.length - 1; i >= 0; i--) {
alert("Username field is required!")
};)
}

One way would be getting your input by id and then validate its value
HTML
<input type="text" id="username" />
<input type="password" id="password" />
JS
function validateForm()
{
if(!document.getElementById("username").value) // true if input value is null, undefined or ""
{
alert("Username field is required!");
}
else if(!document.getElementById("password").value)
{
alert("Username field is required!");
}
}
(i strongly recommend you to use more attractive ways of giving users feedback than JS alerts)

I think all of those checks are incorrect in some for, let's start with the first one:
if(!document.getElementByName("username"))
{
alert("Username field is required!");
}
It's document.getElementsByName() (notice the plural)
The function returns an array of elements, so you'd still need to check for the value of the one you want (probably 0)
This is going to be true always as the field exist, you need to check the value in the input, but right now you are just checking the existence of the input.
Next one is similar:
if(!document.forms[0].username){
alert("Username field is required!");
}
You are checking the existence of the field, not its value
This type of selection is not recommended, you should be using a document.getElementBy... better.
And finally:
if(!document.for (var i = username.length - 1; i >= 0; i--) {
alert("Username field is required!")
};)
It looks like you tried to make a for loop but copy-pasted from above and got this mess... not even going to try to understand why the loop.
Recommendations:
Use the attribute id and read the fields using document.getElementById()
To check if a field has content, check its value: .value
Add an event handler for the form (onsubmit="validateForm()")
Make the form validator return false if one of the fields is incorrect (otherwise the form will be sent even with the incorrect fields)
Optionally: use the HTML5 required attribute.
So the function would look like:
function validateForm()
{
if(document.getElementById("username").value == "")
{
alert("Username field is required!");
return false;
}
// check the other fields
// .....
}

May I suggest something like this instead:
HTML:
<form action="validateForm.html" onSubmit="return validateForm(this)">
<label for="username" name="usernameLabel">* Username:</label>
<input type="text" name="username" id="username" placeholder="Your username" />
<div id="usernameError" style="display:none"></div>
<br/><br/>
<label for="password" name="passwordLabel">* Password:</label>
<input type="password" name="password" />
<div id="passwordError" style="display:none"></div>
<br/><br/>
<input type="submit" value="Submit Form" />
</form>
JS:
function isEmpty (field) {
return field.value === "";
}
function validateForm (form) {
// assume the form to be valid
var isValid = true;
// create a variable to store any errors
var errors = "";
// check if the username is empty
if(isEmpty(form.username)) {
// our assumption is incorrect, the form is invalid
isValid = false;
// append the error message to the string
errors += "Username field is required!\n";
}
if (isEmpty(form.password)) {
isValid = false;
errors += "Password field is required!\n";
}
// display the errors if the form is invalid
if (!isValid) {
alert(errors);
}
return isValid;
}
This way, you are passing the form directly to the validateForm function and can easily access each field using their name properties. You can then check if they're empty by determining what their value contains.

If you need to get the DOM by it name means it will returns an Array so you need to get it by
if(!document.getElementsByName("username")[0].value == ""){
//do ur stuff
}
or
if(!document.getElementById("username").value == ""){
//do ur stuff
}

Related

I can not trigger the alert when the form is empty after developing a clean code in pure JavaScript

The small code in pure HTML, without forgetting to set the method for get:
<form action="#" method="get">
<input id="name" type="text" name="name" placeholder="Nome"><br>
<input id="email" type="text" name="email" placeholder="E-mail"><br>
<textarea id="message" name="name" rows="8" placeholder="Dê-nos um elogio, uma reclamação ou um elogio"></textarea>
<input type="submit" value="Enviar" id="send"><br>
</form>
I refactored and made a clean code of the dirty multiple if-else statements, simplifying. After it, I can not trigger the alert.
The code let send = document.getElementById("send"); checks the code <input type="submit" value="Enviar" id="send"><br>.
Before, in a dirty code, I had many document.getElementById("email").value == "" and simplified to:
const fields = new Set([
'name',
'email',
'message',
]);
I simplified three 'if-else statements along with these if-else statements of identifiers. Firstly, it will check if the fields are empty, go to verify the length, 1 indicates only an empty field and > 1 indicates more empty fields. Else they will check the fields are full and submit.
function alert()
{
let required = fields.value == "";
if (required.length == 1)
{
alert("The field is required!");
required = []
}
else if (required.length > 1)
{ alert("The fields are required!");
required = []
}
else
{
document.getElementById("send").submit();
alert("Thank you! The message was sent successfully")
}
}
Finally, the code send.addEventListener("click", alert) indicates to click the function when sending, and addEventListener will trigger the alert.
Complete code in JavaScript:
let send = document.getElementById("send");
const fields = new Set([
'name',
'email',
'message',
]);
function alert()
{
let required = fields.value == "";
if (required.length == 1)
{
alert("The field is required!");
required = []
}
else if (required.length > 1)
{ alert("The fields are required!");
required = []
}
else
{
document.getElementById("send").submit();
alert("Agradecemos, mensagem enviada com sucesso!")
}
}
send.addEventListener("click", alert)
I will suggest that you create an event listener for invalid on the form. This will be called when one of the required fields empty/invalid (see the required attribute on all the fields). I made a custom alert that shows.
var alert = document.getElementById('alert');
alert.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON')
alert.classList.remove('show');
});
document.forms.form01.addEventListener('submit', e => {
console.log('The form will submit');
});
document.forms.form01.addEventListener('invalid', e => {
e.preventDefault();
alert.classList.add('show');
}, true);
#alert {
display: none;
}
#alert.show {
display: block;
}
<form name="form01" action="#" method="get">
<input id="name" type="text" name="name" placeholder="Nome" required><br>
<input id="email" type="text" name="email" placeholder="E-mail" required><br>
<textarea id="message" name="message" rows="8" placeholder="Dê-nos um elogio, uma reclamação ou um elogio" required></textarea>
<input type="submit" value="Enviar" id="send"><br>
</form>
<div id="alert">The fields are required! <button>OK</button></div>
This is overruling the default behavior in the browser. In any case I think the required attribute is the right way to go.
You may like to do something like this with your function:
function showAlerts(){
var allInputs = document.querySelectorAll('#name, #email, #message');
if(null != allInputs){
for(var i in allInputs){
if(!isNaN(i)){
// here you can check for values, emptiness etc
if(allInputs[i].value.trim() === ''){
// this field is empty
alert('This field is required!');
}
...
}
}
}
}

I'm trying to validate multiple HTML Form inputs with javascript, and change css for invalid ones, what is the best way to do this?

I'm trying to validate an HTML form, trying to check if answers are filled in, and an e-mail is an actual e-mail adress. I want to proceed when all fields are valid. When some fields are not valid, change the css in to another class (so it becomes red to show that it is wrong.)
I have tried to validate each input seperately, but i believe there should be an easier way. Can somebody show me?
Current HTML:
<div class="form-group" id="stage1">
<div class="row">
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</div>
</div
I can't use HTML default validation, since I have created a multi-step form.
Thanks in advance,
Brandon
You can iterate through inputs this will assist validating your messy items:
window.onload = () => {
const allInputs = document.querySelectorAll(".form-control"); // or you may assign custom class or select by input tag..
let isAllvaild = true;
allInputs.forEach((element) => {
if (!validateAll(element.value, element.type)) { isAllvaild = false; break; }
});
if (isAllvaild) {
afterValidation(); // to keep things clean
}
}
function validateAll(value, type) {
if (type === "text") {
} else if (type === "email") {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
let ck = re.test(String(value).toLowerCase());
if (ck) {
// set errors here..
} else {
// maybe remove errors if added previously..
}
return ck;
} else if (type === "phone") {
} else if (type === "other") {
} // add whatever needed..
}
function afterValidation() {
// at this point each input contains valid data.. proceed to next step..
// document.querySelector("#my_id").classList.add("display-block");
// ..
}
you can validate based on their type, so i think u would have two functions, one for email and another one for text fields. for instance:
if(textValidation() && emailValidation()){
submit()
}
emailValidation(){
return email ? true : false
}
textValidation(){
return text ? true : false
}
What about that? It will let you loop through every input and you can also do some specific validations. I know, it is not the smartest function ever, but it can be useful. (ofc you should make some better checking for email pattern (regular expressions are good for that /^.+?#.+..+$/m) and registration number (regex could be cool for that too: /^[\d]*$/m)
function validateInputs ()
{
const inputs = document.querySelectorAll('div[class=row] input');
for (let index = 0; index < inputs.length; index++)
{
const input = inputs[index];
let valid = false;
if (input.value && input.value.trim() !== '')
{
//here you can add specific validations for each id, maybe you can also use switch here
if (input.getAttribute('id') === 'email')
{
//of course, email also need to validate, if dot is present, regular expression might be the best option
if (input.value.indexOf('#') !== -1)
{
valid = true;
}
}
else
{
valid = true;
}
}
if (!valid)
{
input.classList.add('error');
}
else
{
input.classList.remove('error');
}
}
};
window.addEventListener('load', function () {
document.querySelector('button').addEventListener('click', validateInputs)
});
input.error {
background-color: red;
}
<div class="row">
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</div>
<button>validate</button>
For fields like text you need to write your own validation, since it is totally up to you. But in case of fields like email or url you can use build in functions like the HTMLFormElement.checkValidity() method to see if the form contains a field that does not have a valid input, for example a input with type email and a value of foobar would return false from the validity check.
Then you can look inside the form and search for all inputs that are invalid with the :invalid selector in querySelectorAll(). It will return a NodeList with the invalid form elements inside of it.
const form = document.querySelector('form');
form.addEventListener('input', event => {
if (form.checkValidity() === false) {
const invalids = form.querySelectorAll(':invalid');
for (const input of invalids) {
console.log(`${input.id} is invalid`);
}
}
});
<form>
<input type="text" id="firstname" class="form-control" placeholder="Firstname*">
<input type="text" id="lastname" class="form-control" placeholder="Lastname*">
<input type="email" id="email" class="form-control" placeholder="E-mail*">
<input type="url" id="website" class="form-control" placeholder="Website*">
<input type="text" id="regnr" class="form-control" placeholder="Registration number">
</form>
You can use this code between a script tag :
const form = document.querySelector('form'); form.addEventListener('input', event => { if (form.checkValidity() === false) { const invalids = form.querySelectorAll(':invalid'); for (const input of invalids) { console.log(`${input.id} is invalid`); } } });
Or use a Bootstrap classes to validate your form

Text obtained with innerHTML dissapear

I have the following code:
function passVerif() {
if (document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
if (document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="button" name="required" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
As you can see, input type is submit. Because of that (page is refreshing after click on button) the text I want to show disappears after refresh.
As I read on other posts, the simple change from submit to button will do the dew.
But I am suspecting that I messed up the return false and return true instructions in all of my functions.
Is this correct? If they are in a logical way I can avoid the page refresh and continue to use submit? At least until all conditions are met and the form is good to go.
In other words, can someone help me to put return false and true in such way that the page will refresh only if all conditions are met.
Thanks a lot, I am not even a noob.
Codes are copied from different sources on the internet. I am at the very beginning of coding road. Please have mercy :)
I would change it to one validation function and have a bool that is returned based on if it has errored or not:
// Just have one validation function
function validate() {
var errorMessage = ''; // build up an error message
var email = document.forms['form'].email.value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (email === "") {
errorMessage += "Email field is empty!<br>";
} else if (!emailFilter.test(email)) { // this can be else if
errorMessage += "Please enter a valid e-mail address!<br>";
}
if (document.forms['form'].pass.value === "") {
errorMessage += "Password field is empty!<br>"
}
if (errorMessage === '') {
return true; // return true as no error message
} else {
document.getElementById('error-message').innerHTML = errorMessage; // show error message and return false
return false;
}
}
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br>
<input type="submit" name="required" onclick="return validate();">
</form>
</div>
<div id="error-message">
<!-- CAN HAVE ONE ERROR MESSAGE DIV -->
</div>
I tried with your code and I could find the the messages were not getting updated based on the conditions. So I did few modifications to your code to display the message based on which condition fails.
HTML
<div>
<form name="form"> Login<br>
<input type="text" name="email" placeholder="Enter email here" id="input" class="input">Email address<br><br>
<input type="password" name="pass" placeholder="Enter password here" class="input">Password<br><br>
<input type="submit" name="required" value="Submit" onclick="return passVerif(), emailVerif(), validate()">
</form>
</div>
<div id="messagePV"></div>
<div id="messageEV"></div>
<div id="messageV"></div>
JS
function passVerif() {
messagePV.innerHTML = ("")
if(document.forms['form'].pass.value === "") {
messagePV.innerHTML = ("Password field is empty!")
//alert("Password field is empty!");
return false;
}
return true;
}
function emailVerif() {
messageEV.innerHTML = ("")
if(document.forms['form'].email.value === "") {
messageEV.innerHTML = ("Email field is empty!")
//alert("Email field is empty!");
return false;
}
return true;
}
function validate() {
messageV.innerHTML = ("")
var email = document.getElementById("input").value;
var emailFilter = /^([a-zA-Z0-9_.-])+#(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
if (!emailFilter.test(email)) {
messageV.innerHTML = ("Please enter a valid e-mail address!")
//alert('Please enter a valid e-mail address!');
return false;
}
}
By initializing the errormessage filed to empty sting u can maintain the fresh set of error messages.
Jsfiddle: https://jsfiddle.net/85w7qaqx/1/
Hope this helps out.

Showing all error messages at the same time in form validation

Why are my conditional statements not working properly? I want to display bothe error messages at the same time.
function validate() {
if (firstName.value == "") {
document.getElementById('error').innerHTML = "*Field is empty";
return false;
} else if (lastName.value == "") {
document.getElementById('errorTwo').innerHTML = "*Field is empty";
return false;
} else {
return true;
}
}
<form name="form" action="action.php" method="post" onsubmit="return validate()">
<div class="wrapper">
<span>Name</span>
<br>
<input type="text" name="firstName" id="firstName" placeholder="First Name" onfocus="this.placeholder=''" onblur="this.placeholder='First Name'" />
<label id="error"></label>
<br>
<input type="text" name="middleName" id="middleName" placeholder="Middle Name (optional)" onfocus="this.placeholder=''" onblur="this.placeholder='Middle Name (optional)'" />
<input type="text" name="lastName" id="lastName" placeholder="Last Name" onfocus="this.placeholder=''" onblur="this.placeholder='Last Name'" />
<label id="errorTwo"></label>
<br>
<br>
</div>
Your conditional statements are working correctly, your understanding of them is a little off though.
An if / else if statement will stop running when a condition is matched, so if firstName.value is empty, then that if statement will be matched and the code will exit there and not evaluate the rest of the conditions.
You want to use independent conditional statements for each test, and instead of returning either true or false, set a variable to true or false and return that after the conditional checks.
So...
function validate()
{
var valid = true;
if(firstName.value=="")
{
document.getElementById('error').innerHTML="*Field is empty";
valid = false;
}
if(lastName.value=="")
{
document.getElementById('errorTwo').innerHTML="*Field is empty";
valid = false;
}
return valid;
}
Just a note on the code itself, the above comments are mainly correct, if you post your entire code, you'll probably get more helpful responses. Also, you can eliminate the =="" part of the checks and just test the value of the variable as an empty string evaluates to false.
Don't chain the validations together with if-else otherwise if the first name validation fails, then you will never check the last name validation.
Help yourself by quickly creating a JsFiddle :-)
Here it is:
http://jsfiddle.net/23tnpve4/1/
You will easily see some issues by trying:
As others mentioned, missing brackets etc
As others mentioned, if the first test fails the other fields are not checked so errors can by corrected only step by step.
There is no code that refreshes your error DIVs. In a new form check, the error fields have to be cleared first. Checking forms are cycles with several possible start statuses.
Try to collect the status of fields in an array and work them later, something like this:
window.validate = function()
{
var firstName = document.getElementById('firstName');
var lastName = document.getElementById('lastName');
// Clear
firstName.val('');
lastName.val('');
// Check
var errorNames = [];
if(firstName.value=="")
{
errorNames.push('firstName');
}
if(lastName.value=="")
{
errorNames.push('lastName');
}
// Inform
for (var i=0; i<errorNames.length; i++) {
document.getElementById(errorNames[i]).innerHTML="*Field is empty";
}
// Return value
return errorNames.length == 0;
}
The concept of this code will work more intuitively. I haven't checked it against typos, it is a draft, but I do hope it will help you.

Set custom HTML5 required field validation message

Required field custom validation
I have one form with many input fields. I have put html5 validations
<input type="text" name="topicName" id="topicName" required />
when I submit the form without filling this textbox it shows default message like
"Please fill out this field"
Can anyone please help me to edit this message?
I have a javascript code to edit it, but it's not working
$(document).ready(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
e.target.setCustomValidity("Please enter Room Topic Title");
}
};
elements[i].oninput = function(e) {
e.target.setCustomValidity("");
};
}
})
Email custom validations
I have following HTML form
<form id="myform">
<input id="email" name="email" type="email" />
<input type="submit" />
</form>
Validation messages I want like.
Required field: Please Enter Email Address
Wrong Email: 'testing#.com' is not a Valid Email Address. (here, entered email address displayed in textbox)
I have tried this.
function check(input) {
if(input.validity.typeMismatch){
input.setCustomValidity("'" + input.value + "' is not a Valid Email Address.");
}
else {
input.setCustomValidity("");
}
}
This function is not working properly, Do you have any other way to do this? It would be appreciated.
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
You can simply achieve this using oninvalid attribute,
checkout this demo code
<form>
<input type="email" pattern="[^#]*#[^#]" required oninvalid="this.setCustomValidity('Put here custom message')"/>
<input type="submit"/>
</form>
Codepen Demo: https://codepen.io/akshaykhale1992/pen/yLNvOqP
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('Required email address');
}
else if (textbox.validity.typeMismatch){{
textbox.setCustomValidity('please enter a valid email address');
}
else {
textbox.setCustomValidity('');
}
return true;
}
Demo :
http://jsfiddle.net/patelriki13/Sqq8e/
Try this:
$(function() {
var elements = document.getElementsByName("topicName");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function(e) {
e.target.setCustomValidity("Please enter Room Topic Title");
};
}
})
I tested this in Chrome and FF and it worked in both browsers.
Man, I never have done that in HTML 5 but I'll try. Take a look on this fiddle.
I have used some jQuery, HTML5 native events and properties and a custom attribute on input tag(this may cause problem if you try to validade your code). I didn't tested in all browsers but I think it may work.
This is the field validation JavaScript code with jQuery:
$(document).ready(function()
{
$('input[required], input[required="required"]').each(function(i, e)
{
e.oninput = function(el)
{
el.target.setCustomValidity("");
if (el.target.type == "email")
{
if (el.target.validity.patternMismatch)
{
el.target.setCustomValidity("E-mail format invalid.");
if (el.target.validity.typeMismatch)
{
el.target.setCustomValidity("An e-mail address must be given.");
}
}
}
};
e.oninvalid = function(el)
{
el.target.setCustomValidity(!el.target.validity.valid ? e.attributes.requiredmessage.value : "");
};
});
});
Nice. Here is the simple form html:
<form method="post" action="" id="validation">
<input type="text" id="name" name="name" required="required" requiredmessage="Name is required." />
<input type="email" id="email" name="email" required="required" requiredmessage="A valid E-mail address is required." pattern="^[a-zA-Z0-9_.-]+#[a-zA-Z0-9-]+.[a-zA-Z0-9]+$" />
<input type="submit" value="Send it!" />
</form>
The attribute requiredmessage is the custom attribute I talked about. You can set your message for each required field there cause jQuery will get from it when it will display the error message. You don't have to set each field right on JavaScript, jQuery does it for you. That regex seems to be fine(at least it block your testing#.com! haha)
As you can see on fiddle, I make an extra validation of submit form event(this goes on document.ready too):
$("#validation").on("submit", function(e)
{
for (var i = 0; i < e.target.length; i++)
{
if (!e.target[i].validity.valid)
{
window.alert(e.target.attributes.requiredmessage.value);
e.target.focus();
return false;
}
}
});
I hope this works or helps you in anyway.
This works well for me:
jQuery(document).ready(function($) {
var intputElements = document.getElementsByTagName("INPUT");
for (var i = 0; i < intputElements.length; i++) {
intputElements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
if (e.target.name == "email") {
e.target.setCustomValidity("Please enter a valid email address.");
} else {
e.target.setCustomValidity("Please enter a password.");
}
}
}
}
});
and the form I'm using it with (truncated):
<form id="welcome-popup-form" action="authentication" method="POST">
<input type="hidden" name="signup" value="1">
<input type="email" name="email" id="welcome-email" placeholder="Email" required></div>
<input type="password" name="passwd" id="welcome-passwd" placeholder="Password" required>
<input type="submit" id="submitSignup" name="signup" value="SUBMIT" />
</form>
You can do this setting up an event listener for the 'invalid' across all the inputs of the same type, or just one, depending on what you need, and then setting up the proper message.
[].forEach.call( document.querySelectorAll('[type="email"]'), function(emailElement) {
emailElement.addEventListener('invalid', function() {
var message = this.value + 'is not a valid email address';
emailElement.setCustomValidity(message)
}, false);
emailElement.addEventListener('input', function() {
try{emailElement.setCustomValidity('')}catch(e){}
}, false);
});
The second piece of the script, the validity message will be reset, since otherwise won't be possible to submit the form: for example this prevent the message to be triggered even when the email address has been corrected.
Also you don't have to set up the input field as required, since the 'invalid' will be triggered once you start typing in the input.
Here is a fiddle for that: http://jsfiddle.net/napy84/U4pB7/2/
Hope that helps!
Just need to get the element and use the method setCustomValidity.
Example
var foo = document.getElementById('foo');
foo.setCustomValidity(' An error occurred');
Use the attribute "title" in every input tag and write a message on it
you can just simply using the oninvalid=" attribute, with the bingding the this.setCustomValidity() eventListener!
Here is my demo codes!(you can run it to check out!)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>oninvalid</title>
</head>
<body>
<form action="https://www.google.com.hk/webhp?#safe=strict&q=" method="post" >
<input type="email" placeholder="xgqfrms#email.xyz" required="" autocomplete="" autofocus="" oninvalid="this.setCustomValidity(`This is a customlised invalid warning info!`)">
<input type="submit" value="Submit">
</form>
</body>
</html>
reference link
http://caniuse.com/#feat=form-validation
https://www.w3.org/TR/html51/sec-forms.html#sec-constraint-validation
You can add this script for showing your own message.
<script>
input = document.getElementById("topicName");
input.addEventListener('invalid', function (e) {
if(input.validity.valueMissing)
{
e.target.setCustomValidity("Please enter topic name");
}
//To Remove the sticky error message at end write
input.addEventListener('input', function (e) {
e.target.setCustomValidity('');
});
});
</script>
For other validation like pattern mismatch you can add addtional if else condition
like
else if (input.validity.patternMismatch)
{
e.target.setCustomValidity("Your Message");
}
there are other validity conditions like rangeOverflow,rangeUnderflow,stepMismatch,typeMismatch,valid
use it on the onvalid attribute as follows
oninvalid="this.setCustomValidity('Special Characters are not allowed')

Categories

Resources