I hope somebody can help me find the error in this code, i need to use simple js to create a form that only submits if there are no errors, The user name must be a valid email. The password and retyped password must be 8 characters and include one uppercase, one lowercase and one numeric. The password
and the retyped password must match. I need to make use of a regular
expression to constrain the password.
If the data rules are violated, a appropriate error messages should be displayed
and the form should be stopped from submitting.Can someone help me with why it is not doing what it is supposed to? Im still new to js and any hel would be appreciated.
function handleInvalidities(input) {
let errMsg = " ";
if (!input.validity.paternMismatch) {
errMsg = "Invalid entry. Enter your details in the format shown.";
}
if (!input.validity.paternMismatch) {
errMsg = "Invalid entry. This field cannot be empty. Please enter a value.";
}
return errMsg;
}
function displayInvalidities(errMsg, elem) {
let elemPos = document.getElementById(elem);
let errElem = document.createElement("span");
errElem.setAttribute("class", "error");
let errText = document.createTextNode(errMsg);
errElem.appendChild(errText);
elemPos.parentNode.insertBefore(errElem, elemPos.nextSibling);
}
function cleanUpErrors() {
let errors = document.getElementsByClassName("error");
for (let i = 0; i < errors.length; i++) {
errors[i].style.display = "none";
}
}
window.onload = () => {
let theForm = document.getElementById("loginform");
theForm.addEventListener("submit");
(event) => {
let stopSubmit = false;
cleanedUpErrors();
for (let i = 0; i < theForm.elements.length; i++) {
if (!theForm.elements[i].checkValidity()) {
displayInvalidities(handleInvalidities(theForm.elements[i]), theForm.Elements[i].id);
stopSubmit = true;
}
}
if (stopSubmit) {
event.preventDefault();
}
}, (false);
}
<section>
<h1>Form: validated using Javascript</h1>
<p>Try entering the following:</p>
<ul>
<li>Password longer or shorter than 8 characters and/or without an uppercase, lowercase or a numeric.</li>
<li>Passwords that do not match</li>
</ul>
<h2>Register</h2>
<p>* = Required Field</p>
<div id="formcontainer">
<form id="regsiterdetails" action="fma_t3confirm.html">
<div>
<label for="username">* Userame:</label>
<input type="text" id="username">
</div>
<div>
<label for="password">* Password (Must be 8 characters and include one uppercase, one lowercase and one numeric):</label>
<input type="password" id="password">
<input type="checkbox" id="showpasswords">
<label id="showpasswordslabel" for="showpasswords">Show passwords</label>
</div>
<div>
<label for="retypedpassword">* Retype your password:</label>
<input type="password" id="retypedpassword">
<span id="passwordmatcherror"></span>
</div>
<div>
<button type="submit" id="registerButton">Register</button>
</div>
</form>
</div>
</section>
You need to fix your event handlers and spelling (Elements) and form ID (registerdetails) and spelling of function names like cleanUpErrors
window.addEventListener("load", () => {
document.getElementById("registerdetails").addEventListener("submit", event => {
const theForm = event.target;
let stopSubmit = false;
cleanUpErrors();
for (let i = 0; i < theForm.elements.length; i++) {
if (!theForm.elements[i].checkValidity()) {
displayInvalidities(handleInvalidities(theForm.elements[i]), theForm.elements[i].id);
stopSubmit = true;
}
}
if (stopSubmit) {
event.preventDefault();
}
})
})
You are setting event listener without any function. Change in your code like this:
window.onload = () => {
let theForm = document.getElementById("regsiterdetails");
theForm.addEventListener("submit",(event) => {
let stopSubmit = false;
cleanedUpErrors();
for (let i = 0; i < theForm.elements.length; i++) {
if (!theForm.elements[i].checkValidity()){
displayInvalidities(handleInvalidities(theForm.elements[i]), theForm.Elements[i].id);
stopSubmit = true;
}
}
if (stopSubmit) {
event.preventDefault();
}
}, (false);
)
}
Also check your code as there is no element with id loginform. I think you should use regsiterdetails instead of loginform.
There was no form element with the id that you're trying to get. Try to get with the actual id which is regsiterdetails and fix your addEventListener parameter list.
function handleInvalidities(input) {
let errMsg = " ";
if (!input.validity.paternMismatch) {
errMsg = "Invalid entry. Enter your details in the format shown.";
}
if (!input.validity.paternMismatch) {
errMsg = "Invalid entry. This field cannot be empty. Please enter a value.";
}
return errMsg;
}
function displayInvalidities(errMsg, elem) {
let elemPos = document.getElementById(elem);
let errElem = document.createElement("span");
errElem.setAttribute("class", "error");
let errText = document.createTextNode(errMsg);
errElem.appendChild(errText);
elemPos.parentNode.insertBefore(errElem, elemPos.nextSibling);
}
function cleanUpErrors() {
let errors = document.getElementsByClassName("error");
for (let i = 0; i < errors.length; i++) {
errors[i].style.display = "none";
}
}
window.onload = () => {
let theForm = document.getElementById("regsiterdetails");
theForm.addEventListener("submit", (event) => {
let stopSubmit = false;
cleanedUpErrors();
for (let i = 0; i < theForm.elements.length; i++) {
if (!theForm.elements[i].checkValidity()) {
displayInvalidities(handleInvalidities(theForm.elements[i]), theForm.Elements[i].id);
stopSubmit = true;
}
}
if (stopSubmit) {
event.preventDefault();
}
}, (false));
}
<section>
<h1>Form: validated using Javascript</h1>
<p>Try entering the following:</p>
<ul>
<li>Password longer or shorter than 8 characters and/or without an uppercase, lowercase or a numeric.</li>
<li>Passwords that do not match</li>
</ul>
<h2>Register</h2>
<p>* = Required Field</p>
<div id="formcontainer">
<form id="regsiterdetails" action="fma_t3confirm.html">
<div>
<label for="username">* Userame:</label>
<input type="text" id="username">
</div>
<div>
<label for="password">* Password (Must be 8 characters and include one uppercase, one lowercase and one numeric):</label>
<input type="password" id="password">
<input type="checkbox" id="showpasswords">
<label id="showpasswordslabel" for="showpasswords">Show passwords</label>
</div>
<div>
<label for="retypedpassword">* Retype your password:</label>
<input type="password" id="retypedpassword">
<span id="passwordmatcherror"></span>
</div>
<div>
<button type="submit" id="registerButton">Register</button>
</div>
</form>
</div>
</section>
Related
I currently have a form with a few variables like username, password, and email which sends the data to a node.js server. Before sending the data, I have a few checks such as whether the inputs are valid and whether the email already exists in my file. The checking aspect of my code works, however the javascript function which I use to check returns before opening the file to check for duplicate emails. I feel that if I could somehow make the onsubmit function asynchronous, that would help.
Here is my code and the segment where I check for duplicate emails is near the end:
<html>
<body>
<form id='form' action="/signup.html" method="POST" onsubmit="return submitIt();">
<div style="text-align:center">
<label for="name">Full Name</label><br>
<input type="text" size="100" id="name" name="name" placeholder="Enter Your Full Name: "><br><br>
<label for="email">Email</label><br>
<input type="text" size="100" id="email" name="email" placeholder="Enter Your Email: "><br><br>
<label for="password">Password</label><br>
<input type="text" size="100" id="password" name="password" placeholder="Enter Your Password: "><br><br>
<button type="submit" id="submit">Submit</button>
</div>
</form>
</body>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
var ret = true;
async function submitIt() {
let name = document.getElementById("name").value;
let email = document.getElementById("email").value;
let password = document.getElementById("password").value;
if (name == "" || name.length < 4) {
document.getElementById("name").value = "";
document.getElementById("name").placeholder = "Please enter a real name";
ret = false;
}
if (email == "" || email.length < 4) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Please enter a real email";
ret = false;
}
if (ret) {
let found = false;
for (let i = 0; i < email.length; i++) {
if (email[i] == '#') {
found = true;
}
}
if (!found) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Please enter a real email";
ret = false;
}
}
if (password.length < 5) {
document.getElementById("password").value = "";
document.getElementById("password").placeholder = "Password must be atleast 5 characters.";
ret = false;
}
await $.ajax({
type:"POST",
url:'/getUsers',
dataType: "text",
success: function(content) {
let contents = content.split('\n');
for (let i = 0; i < contents.length; i += 3) {
if (contents[i] == email) {
document.getElementById("email").value = "";
document.getElementById("email").placeholder = "Email already in use.";
ret = false;
}
}
}
});
return ret;
}
</script>
</head>
</html>
Any help would be greatly appreciated!
Have you tried moving onSumbmit call from form to the button?
const submitButton = document.getElementById(***)
submitButton.addEventListener('click', () => {your code})
Another way could be preventing default behavior of the submit form.
async function submitIt(event) {
event.preventDefault;
event.stopImmediatePropagation;
....your code....
}
I don't have access to a PC right now to check it, but one of the provided solutions should work. Cheers!
This question already has answers here:
How to prevent form from being submitted?
(11 answers)
Closed last year.
I have created 3 functions to cilentside validate a form for its name, email, and website, I would like to create a 4th function that checks if the outcome of the 3 first functions is true, we submit the form, if the outcome of any of them is false, the form doesn't get submitted. Below is my attempt for the JavaScript.
The purpose of this question is to learn how to use a 4th function to check the other 3 functions returns.
//validating name, email, website:
function nameValidation() {
var valid = true;
var name = document.getElementById("name1").value;
var validname = /^[a-zA-Z\s]*$/;
if (name == "") {
document.getElementById("errorMsg2").innerHTML = "* Name is required";
valid = false;
} else if (name.match(validname)) {
valid = true;
} else {
document.getElementById("errorMsg2").innerHTML = "* Only letters and white spaces allowed";
valid = false;
}
return valid;
}
function emailValidation() {
var valid = true;
var validEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
var email = document.getElementById("email1").value;
if (email == "") {
document.getElementById("errorMsg3").innerHTML = "* Email is required";
valid = false;
} else if (email.match(validEmail)) {
valid = true;
} else {
document.getElementById("errorMsg3").innerHTML = "*Please enter a valid email.";
valid = false;
}
return valid;
}
function websiteValidation() {
var valid = true;
var validWebsite = /\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i;
var website = document.getElementById("website1").value;
if (website == "" || website.match(validWebsite)) {
valid = true;
} else {
document.getElementById("errorMsg4").innerHTML = "* Website is required";
valid = false;
}
return valid;
}
// function for form submission:
function formSubmit() {
if (nameValidation() == true && emailValidation() == true && websiteValidation() == true) {
return true;
} else {
return false;
}
}
document.getElementById("submit").addEventListener("click", () => {
console.log("Final result:", formSubmit());
});
<div>
<div id="errorMsg2"></div>
<input type="text" id="name1" />
</div>
<div>
<div id="errorMsg3"></div>
<input type="text" id="email1" />
</div>
<div>
<div id="errorMsg4"></div>
<input type="text" id="website1" />
</div>
<div>
<input type="submit" id="submit" />
</div>
Delete all of the JavaScript. This is the only HTML you need:
<input type="text" id="name1" pattern="[a-zA-Z\s]+" title="Letters and spaces only" required />
<input type="email" id="email1" required />
<input type="url" id="website1" required />
<input type="submit" id="submit" />
HTML5 Form validation has been around for a very long time at this point.
So I am practicing Javascript and right now I am trying to implement form validation.
One of the issues I am having is that when I click on the button when all of the input fields are empty, the first one (Full Name) only highlights and displays a message (Please checkout snippet). I was wondering is that how it works - can only one message be displayed at a time or is there a way to get all of the input fields to change color and display messages for each empty field?
function validateForm(e) {
const eName = document.getElementById("FullName");
const eMail = document.getElementById("Email");
const ePhone = document.getElementById("PhoneNumber");
const ePass = document.getElementById("Password");
const eCnfmPass = document.getElementById("ConfirmPassword");
const phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
const fullNameText = "Oops, please fill out your name";
const emailText = "Please enter a valid email";
const phoneText = "Please enter a valid phone number";
const passText = "Please enter a valid password";
const confirmText = "Please confirm your password";
//Name input validation - If input is left empty
if (eName.value === "") {
e.preventDefault();
document.getElementById("FullName").style.borderColor = "red";
document.getElementById("FullNameLabel").innerHTML = fullNameText;
document.getElementById("FullNameLabel").style.color = "red";
return false;
}
//Email input validation - If input is left empty
if (eMail.value === "") {
e.preventDefault();
document.getElementById("Email").style.borderColor = "red";
document.getElementById("EmailLabel").innerHTML = emailText;
document.getElementById("EmailLabel").style.color = "red";
return false;
}
//Phone number input validation - If input is left empty
if (ePhone.value === "") {
e.preventDefault();
document.getElementById("PhoneNumber").style.borderColor = "red";
document.getElementById("PhoneNumberLabel").innerHTML = phoneText;
document.getElementById("PhoneNumberLabel").style.color = "red";
return false;
}
//Phone number input validation - checks to see if there is a missing number or character that is not a number
if (ePhone.value.match(phoneno)) {
return true;
} else {
alert("Please check your phone number and enter it again")
// document.getElementById("PhoneNumber").style.borderColor = "red";
// document.getElementById("PhoneNumberLabel").innerHTML = phoneText;
// document.getElementById("PhoneNumberLabel").style.color = "red";
return false;
}
//Password input validation - If input is left empty
if (ePass.value === "") {
e.preventDefault();
document.getElementById("Password").style.borderColor = "red";
document.getElementById("PasswordLabel").innerHTML = passText;
document.getElementById("PasswordLabel").style.color = "red";
return false;
}
//Confirm password input validation - If input is left empty
if (eCnfmPass.value === "") {
e.preventDefault();
document.getElementById("ConfirmPassword").style.borderColor = "red";
document.getElementById("ConfirmPswdLabel").innerHTML = confirmText;
document.getElementById("ConfirmPswdLabel").style.color = "red";
}
}
//Checks to make sure that both password and confirm passwords match
var passConfirm = function() {
if (document.getElementById("Password").value ==
document.getElementById("ConfirmPassword").value) {
document.getElementById("Message").style.color = "green";
document.getElementById("Message").style.fontWeight = "Heavy";
document.getElementById("Message").innerHTML = "Passwords match!"
} else {
document.getElementById("Message").style.color = "red";
document.getElementById("Message").style.fontWeight = "Heavy";
document.getElementById("Message").innerHTML = "Passwords do NOT match!"
}
}
<div class="container">
<form class="form" onsubmit="validateForm(event)">
<div>
<label id="FullNameLabel">Full Name</label></br>
<input type="text" placeholder="John Doe" id="FullName" />
</div>
<div>
<label id="EmailLabel">Email</label></br>
<input type="text" placeholder="johndoe#email.com" id="Email" />
</div>
<div>
<label id="PhoneNumberLabel">Phone Number</label></br>
<input type="text" placeholder="(123) 456-7890" id="PhoneNumber" />
</div>
<div>
<label id="PasswordLabel">Password</label></br>
<input name="Password" id="Password" type="Password" placeholder="Password" onkeyup='passConfirm();' />
</div>
<div>
<label id="ConfirmPswdLabel">Confirm Password</label></br>
<input name="ConfirmPassword" id="ConfirmPassword" type="Password" placeholder="Confirm Password" onkeyup='passConfirm();' />
</div>
<span id="Message"></span>
<button type="submit" value="submit">Sign Me Up!</button>
</form>
</div>
You have too much javascript code, you can simplify that, alot.
to check if any of the inputs are empty, you can first store all the inputs in a variable like that:
let inputs = document.querySelectorAll('.form input') //This will make a Nodelist array of all the inputs inside the form.
let labels = document.querySelectorAll('.form label') //This will make a Nodelist array of the label tags inside the form
after that you can loop through the inputs array to find if any of the inputs are empty:
for (let i = 0; i < inputs.length; i++) {
if (inputs.value.length == 0) {
inputs[i].style.borderColor = 'red'
label[i].textContent = 'Please fill in this input'
}
}
Require your inputs. Why go through all that trouble making sure they're filled out?
<input required>
First off, if this is against the rules, or frowned upon I'm very sorry and feel free to downvote/close. I'm desperately stuck.
I'm having trouble with an HTML page I wrote which is supposed to consist of inputs with certain requirements, adding div's to display error messages , and automatically update those error messages onblur. The assignment was made to test our javascript skills, and thus must be completely validated through javascript.
Here are a few of the guidelines...
validating the form for four separate things:
presence of required fields
equality of password fields
conformance to a password policy (one uppercase, one number, length > 7)
validity of the email address
When any one of these are violated, I should deactivate the form’s submit button so that it is not clickable and add a child "div" to the error-display containing an error message describing the situation.
The code seems correct to me, and works spontaneously, but i believe since javascript is looked at one line at a time it isn't displaying error messages correctly or even getting to certain parts of my code at all.
Here is my large chunk of javascript code, I am mainly looking for a way to break out of these if/else blocks that my code seems stuck in:
function formValidation() {
var form = document.getElementById('project-form');
var username = document.getElementById('username');
var name = document.getElementById('name');
var phone = document.getElementById('phone-number');
var email = document.getElementById('email');
var password = document.getElementById('password');
var passwordConfirmation = document.getElementById('password-confirmation');
var submit = document.getElementById('submit-btn');
var errorDisplay = document.getElementById('error-display');
var missingFieldBoolean = false;
var passwordMismatchBoolean = false;
var isUpper = false;
var isNumber = false;
var passwordLength = false;
var validEmail = false;
var createDiv = document.createElement("DIV");
var passwordConstraint, passwordConstraintError;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
//Checks all fields for empty values and updates error div
if (username.value.length == 0 || name.value.length == 0 || email.value.length == 0 || password.value.length == 0 || passwordConfirmation.value.length == 0) {
missingField = errorDisplay.appendChild(createDiv);
missingField.setAttribute("id", "required-field-error");
missingFieldError = document.getElementById('required-field-error');
missingFieldError.innerHTML = "Missing Fields: ";
if (username.value.length == 0) {
missingFieldError.innerHTML += "Username - ";
}
if (name.value.length == 0) {
missingFieldError.innerHTML += "Full Name - ";
}
if (email.value.length == 0) {
missingFieldError.innerHTML += "Email - ";
}
if (password.value.length == 0) {
missingFieldError.innerHTML += "Password - ";
}
if (passwordConfirmation.value.length == 0) {
missingFieldError.innerHTML += "Password Confirmation - ";
}
} else {
errorDisplay.removeChild(missingFieldError);
missingFieldBoolean = true;
}
//Checks password vs password confirmation to see if they match, else updates error div
if (password.value != passwordConfirmation.value) {
passwordMismatch = errorDisplay.appendChild(createDiv);
passwordMismatch.setAttribute("id", "password-mismatch-error");
passwordMismatchError = document.getElementById('password-mismatch-error');
passwordMismatchError.innerHTML = "The Password and Password Confirmation do not match. Please re-enter.";
} else {
errorDisplay.removeChild(passwordMismatchError);
passwordMismatchBoolean = true;
}
//for loop to iterate through password to check for required characters, else updates error div
for (var index = 0; index < password.value.length; index++) {
if (password.value.charAt(index) == password.value.charAt(index).toUpperCase) {
isUpper = true;
}
if ("0123456789".indexOf(password.value.charAt(index)) > -1) {
isNumber = true;
}
if (password.value.length > 7) {
passwordLength = true;
} else {
passwordConstraint = errorDisplay.appendChild(createDiv);
passwordConstraint.setAttribute("id", "password-constraint-error");
passwordConstraintError = document.getElementById('password-constraint-error');
passwordConstraintError.innerHTML = "The Password must be 8 characters long, with one uppercase letter and one number. ";
}
}
//checks if password constraints are met and removes div if true
if (isUpper && isNumber && passwordLength) {
errorDisplay.removeChild(passwordConstraintError);
}
//checks email, if invalid it adds error div, else it removes the div ***NOT WORKING***
if (!(mailformat.test(email.value))) {
invalidEmail = errorDisplay.appendChild(createDiv);
invalidEmail.setAttribute("id", "invalid-email-error");
invalidEmailError = document.getElementById('invalid-email-error');
invalidEmailError.innerHTML = "Please enter a valid email address.";
} else {
errorDisplay.removeChild(invalidEmailError);
validEmail = true;
}
//if all requirements are met and true, submit button becomes enabled ***NOT WORKING***
if (isUpper && isNumber && passwordLength && missingFieldBoolean && passwordMismatchBoolean && validEmail) {
submit.disabled = false;
}
}
<div id="error-display"></div>
<br>
<form id="project-form" action="/submit.php" method="get" onclick="formValidation()">
<label>Username:</label>
<input id="username" type="text" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Full Name:</label>
<input id="name" type="text" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Phone Number:</label>
<input id="phone-number" type="tel">
<br>
<label>Email:</label>
<input id="email" type="email" onblur="formValidation()" required>
<c>*</c>
<br>
<label>Password:</label>
<input id="password" type="password" required onblur="formValidation()">
<c>*</c>
<br>
<label>Confirm Password:</label>
<input id="password-confirmation" type="password" required onblur="formValidation()">
<c>*</c>
<br>
<br>
<input id="submit-btn" type="submit" value="Submit" disabled>
</form>
Thanks a lot in advance, and again sorry if i'm breaking the rules.
I would put all the inputs into an object instead, that way you could automatically iterate over the object.
const fieldValues = [
'username',
'name',
'phone-number',
'email',
'password',
'password-confirmation',
]
.reduce((fieldsSoFar, fieldName) => {
fieldsSoFar[fieldName] = document.getElementById(fieldName).value;
return fieldsSoFar;
}, {});
const missingFieldsStr =
Object.entries(fieldValues)
.filter(([, fieldValue]) => fieldValue.length === 0)
.map(([fieldName]) => {
const words = fieldName.split(' ');
const upperWords = words.map(word => word.slice(0, 1).toUpperCase() + word.slice(1))
return upperWords;
})
.join(', ');
if (missingFieldsStr) {
// display it
}
// skipping some lines...
const hasUpper = /[A-Z]/.test(fieldValues.password);
const hasNumber = /[0-9]/.test(fieldValues.password);
And so on.
Don't implicitly create global variables - strongly consider using a linter.
Only use innerHTML when you're deliberately using or inserting HTML markup (which can have security and encoding problems). When you're setting or retrieving text values, use textContent instead.
I got most of this form validation to work properly but the only issue is that when the form detects an error on submit and the user corrects the mistake, the error text won't go away. This can be confusing for the user but I can't seem to figure out a way to make the error text disappear with the way that I am doing this. Also I know I have the option of PHP validation but there is a few reasons why I want to use this front end validation. Here is the whole validation script for the form. The submit portion is at the bottom:
JavaScript/jQuery
var valid = 0;
function checkName(elem) {
//gather the calling elements value
var val = document.getElementById(elem.id).value;
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span>Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
valid++;
}
}
function checkEmail(elem) {
var val = document.getElementById(elem.id).value;
//Check email format validity
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,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
valid++;
}
}
function checkMessage(elem) {
var val = document.getElementById(elem.id).value;
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
valid++;
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
function checkSubmit() {
if (valid == 3) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
//If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if (valid < 3) {
document.getElementById("errorSubmit").innerHTML = "<span>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
HTML Form
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="cform" id="contact-form">
<form id="form13" name="form13" role="form" class="contactForm" accept-charset="UTF-8" autocomplete="off" enctype="multipart/form-data" method="post" novalidate
action="https://Some3rdPartyPOSTService">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" name="Field1" class="form-control" id="name" placeholder="Tony Stark" onblur="checkName(this)"/>
<span id="errorName" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="email">Your Email</label>
<input type="email" class="form-control" name="Field4" id="email" placeholder="" data-rule="email" data-msg="Please enter a valid email" onblur="checkEmail(this)"/>
<span id="errorEmail" style="margin-left:10px;"></span>
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" name="Field3" id="message" rows="5" data-rule="required" data-msg="Please write something here" onblur="checkMessage(this)"></textarea>
<span id="errorMessage" style="margin-left:10px;"></span>
</div>
<span id="errorSubmit" style="margin-left:10px;"></span>
<button type="submit" class="btn btn-theme pull-left">SEND MESSAGE</button>
</form>
</div>
</div>
<!-- ./span12 -->
</div>
</div>
</section>
Simply put your check on onChange event callback, if:
var x = getElementById("formid"); // then add a listener
x.addEventListener('change', function () {
callback with your code that examines the form
});
Or listen for a specific text box change event, that would be the simplest way, and look for a way to disable submit if the conditions aren't met.
Add an onchange event to your text inputs that will remove the error message.
Rather than making a count of valid fields, I would also check for the existence of error messages. This will make it easier to add more fields to your form.
function checkName(e) {
//gather the calling elements value
var val = $(e.target).val();
//Check length
if (val.length<1) {
document.getElementById("errorName").innerHTML = "<span class="errmsg">Don't forget your name.</span>";
} else if (val.length>40){
document.getElementById("errorName").innerHTML = "<span class='errmsg'>This doesn't look like a name.</span>";
//If valid input increment var valid.
} else {
document.getElementById("errorName").innerHTML = "";
}
}
function checkEmail(e) {
var val = $(e.target).val();
//Check email format validity
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,}))$/;
if (!re.test(val)) {
document.getElementById("errorEmail").innerHTML = "<span class='errmsg'>Please enter a valid email.</span>";
} else {
document.getElementById("errorEmail").innerHTML = "";
}
}
function checkMessage(e) {
var val = $(e.target).val();
if (val.length<1) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like you forgot the message.</span>";
} else if (val.length>2000) {
document.getElementById("errorMessage").innerHTML = "<span class='errmsg'>It looks like your message is too long.</span>";
} else {
document.getElementById("errorMessage").innerHTML = "";
}
}
//Contact: jQuery check for null/empty/errors
$(document).ready(function() {
$('#name').change(checkName);
$('#email').change(checkEmail);
$('#message').change(checkMessage);
function checkSubmit() {
if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "";
}
}
}
/If errors when submitting display message
$('#form13').submit(function(submit) {
if ($.trim($("#name").val()) === "" || $.trim($("#email").val()) === "" || $.trim($("#message").val()) === "") {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please fill out all the form fields.</span>";
submit.preventDefault();
} else if ($('form .errmsg').length > 0) {
document.getElementById("errorSubmit").innerHTML = "<span class='errmsg'>Please check the errors above.</span>";
submit.preventDefault();
}
})
});
Since you were already using jQuery, I modified the code to use more of the jQuery functionality to make things easier. Now when a form field is modified and the element loses focus, the validation will occur immediately. We also no longer need to know how many error messages could potentially appear (though you never had a decrement operation for corrected values so the valid could become greater than 3). Instead we just make sure that there isn't more than 0 of them.
I've removed your onblur html attributes and replaced them by JavaScript keyup events. This will allow your script to check everything as soon as the user type something :
document.getElementById("message").addEventListener('keyup', function () {
checkMessage(this);
});
document.getElementById("email").addEventListener('keyup', function () {
checkEmail(this);
});
document.getElementById("name").addEventListener('keyup', function () {
checkName(this);
});
JSFIDDLE