I have a form that contains information fields for potential customers. Spammers are entering web addresses in the address field. I want to have an error message when the field contains "http://"
Here is the form code:
<label>First Name:</label> <input id="first_name" name="first_name" type="text" size="20" />
<label>Last Name:</label> <input id="last_name" name="last_name" type="text" size="20" />
<label>Address:</label> <input name="address" type="text" size="30" />
<label>City, State Zip:</label> <input name="city" type="text" size="20" value="City, State Zip"/>
<label>Phone Number:</label> <input name="phone" type="text" size="20" />
<label>Email:</label> <input id="email" name="email" type="text" size="30" />
Here is the error code I have:
function validateForm(){
message = '';
error = 0;
if (document.contact_form.first_name.value == '') {
message = 'First name is a required field\n';
error = 1;
}
if (document.contact_form.last_name.value == '') {
message = message + 'Last name is a required field\n';
error = 1;
}
if (document.contact_form.phone.value == '') {
message = message + 'Phone Number is a required field\n';
error = 1;
}
if (document.contact_form.email.value == '') {
message = message + 'Email is a required field\n';
error = 1;
}
if (WHAT GOES HERE TO SHOW THAT THE FIELD CAN'T CONTAIN ANY VARIATION OF 'http://?') {
message = message + 'That is not a valid address\n';
error = 1;
}
if (error) {
alert(message);
return false;
} else {
return true;
}
}
Use a regular expression.
if (/^http:\/\//.test(document.contact_form.email.value)) {
message = message + 'That is not a valid address\n';
error = 1;
}
I'm assuming you only want to test for http:// at the beginning of the string (just remove ^ if you want to test for it anywhere in the string).
You can use indexOf function as below:
if(document.contact_form.address.value.indexOf("http://") !== -1) {
message = message + "That is not a valid address\n";
error = true;
}
indexOf will return -1 if the value specified in the indexOf function parameter is not found in the string.
References:
http://www.w3schools.com/jsref/jsref_indexof.asp
How to check whether a string contains a substring in JavaScript?
Give your inputs in question a class, maybe something other than what I've done.
give your id's a useful name.
Makes coding a lot easier.
function validate() {
var inputs = document.querySelectorAll('.inputs'),
i = 0;
for (; i < inputs.length; i++) {
if (inputs[i].value == '') {
message = message + ' ' + inputs[i].id + ' is a required field\n';
};
};
};
Related
Guys I coded this in html and js. It is just simple three inputs, NAME, EMAIL and PASSWORD. I validated this simple form in javascript but it is not working as expected. I wanted that if I give wrong input to any one of three inputs, it should alert me "Please enter valid credentials." and if I give right input to all of these, It should alert me "Congrats! your form submitted.".
The validation which I gave to NAME field is if length of name is less than 1, it should return false, else true. The validation which I gave to PASSWORD field is same as NAME field and you can see the validation which I gave to all field in my code below. When I give wrong input to only one field, it is still showing me "Congrats! your form submitted."
It is not working as expected!
function ValidateForm(username, email, password)
{
if ((validateusername(username) || validateemail(email) || validatepassword(password))==false)
{
alert("Please Enter Valid Credentials.")
return false
}
else if ((validateusername(username))==true && (validateemail(email))==true && (validatepassword(password))==true)
{
alert("Congrats! your form submitted.")
}
}
function validateemail(email)
{
var x = email.value;
var atposition = x.indexOf("#");
var dotposition = x.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
return false;
}
else
{
return true
}
}
function validateusername(username)
{
if (username.length<1)
{
return false;
}
else
{
return true
}
}
function validatepassword(password)
{
if (password.length<1)
{
return false;
}
else
{
return true
}
}
<form name="myForm">
<input type="text" name="Name" placeholder="Enter Name">
<input type="text" name="EmailAddr" placeholder="Enter Email">
<input type="text" name="Password" placeholder="Enter Password">
<button type="submit" onclick="ValidateForm(document.myForm.Name, document.myForm.EmailAddr, document.myForm.Password)">Submit</button>
</form>
The problem is your if statement condition.
(validateusername(username) || validateemail(email) || validatepassword(password))==false
is the same as
!validateusername(username) && !validateemail(email) && !validatepassword(password)
so you're saying it should only be considered invalid if all 3 validations fail.
This function can be cleaned up and fixed at the same time:
function ValidateForm(username, email, password)
{
if (!validateusername(username) || !validateemail(email) || !validatepassword(password)) {
alert("Please Enter Valid Credentials.")
return false
}
else {
alert("Congrats! your form submitted.")
}
}
That's all you need. If any one of those fails, then the form fails. Otherwise (else) it's fine. You don't need to re-check again.
One improvement you can make is to take as few arguments as necessary without impeding clarity. This function is called "validate form" so I'd expect the form to be the argument, like this:
ValidateForm(document.myForm)
Which is easy to accommodate internally:
function ValidateForm(form)
{
if (!validateusername(form.username) || !validateemail(form.email) || !validatepassword(form.password)) {
alert("Please Enter Valid Credentials.")
return false
}
else {
alert("Congrats! your form submitted.")
}
}
Which requires renaming your form fields to be consistent:
<input type="text" name="name" placeholder="Enter Name">
<input type="text" name="email" placeholder="Enter Email">
<input type="text" name="password" placeholder="Enter Password">
Tip: Try and have one and only one name for your things. Calling it variously Name or name is really counter-productive.
I would avoid inlining events.
Take a look.
document.myForm.addEventListener("submit", validateForm);
function validateForm(event) {
event.preventDefault();
const {
Name: username,
EmailAddr: email,
Password: password,
} = document.myForm;
if (!validateUsername(username) ||
!validateEmail(email) ||
!validatePassword(password)) {
console.log("Please Enter Valid Credentials.")
return;
}
console.log("Congrats! your form submitted.");
}
function validateEmail(emailField) {
const x = emailField.value;
const atposition = x.indexOf("#");
const dotposition = x.lastIndexOf(".");
if (atposition < 1 ||
dotposition < atposition + 2 ||
dotposition + 2 >= x.length) {
return false;
}
return true
}
function validateUsername(username) {
if (username.length < 1) {
return false;
}
return true;
}
function validatePassword(password) {
if (password.length < 1) {
return false;
}
return true;
}
<form name="myForm">
<input type="text" name="Name" placeholder="Enter Name">
<input type="text" name="EmailAddr" placeholder="Enter Email">
<input type="text" name="Password" placeholder="Enter Password">
<button type="submit">Submit</button>
</form>
I am trying to pass data from a form into a Google Apps Script but when I press submit I am greeted by I blank screen.
Form:
<div id="nameDiv">
<form action="https://script.google.com/a/umbc.edu/macros/s/AKfycbztum1ImJZeXXYt0fFhwOAMUsB5zCsJQohrum4W7qiH/dev">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="google.script.run.nameSearch()">
</form>
</div>
Script:
function nameSearch(){
try {
var firstName = document.getElementById("fname").value
var lastName = document.getElementById("lname").value
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15]
}
}
document.getElementById('nameDiv').innerHTML =
"<center>Last Name:" + lastName + "</center>" +
"</br><center>First Name:" + firstName + "</center>"
} catch(e) {
alert(e)
}
}
I am trying to pass this data to the script so that it can use it to search a google sheet so I cannot just place the script in the html as a client side script. Any thought?
All the HTML-related methods (getElementById, innerHTML, etc.) should be in client-side script, and Apps Script methods should be in the server-side.
If I understand you correctly, you want to do the following:
When this form gets submitted, look for the row whose columns K and L match the inputted fields (indexes 10 and 11 from inputData array).
For this row, return data from columns O and P (indexes 14 and 15 from inputData array).
Write this returned data to the HTML.
If all this is correct, then you could do this:
Add an onclick event in the submit input that will fire a client-side function (a function that is declared inside the tags in the HTML). There is no need to use a for this. The HTML body could be something like this:
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
From this client-side function called clientNameSearch(), retrieve the values from fname and lname, and use these as parameters when you call a server-side function called nameSearch):
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
This server-side function iterates through all rows with content in the spreadsheet, and returns the result for the first row whose columns K and L match the inputted data:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
This result is then passed as a parameter to a client-side function called onSuccess via a success handler. This is necessary since server-side functions called by google.script.run don't return anything directly, as specified here. Then onSuccess writes the result to the HTML:
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
Full code:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div id="nameDiv">
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname">
<label for="lname">Last Name</label>
<input type="text" id="lname" name="lastname" >
<input type="submit" value="Submit" onclick="clientNameSearch()">
</div>
</body>
<script>
function clientNameSearch() {
var firstName = document.getElementById("fname").value;
var lastName = document.getElementById("lname").value;
google.script.run.withSuccessHandler(onSuccess).nameSearch(firstName, lastName);
}
function onSuccess(result) {
document.getElementById('nameDiv').innerHTML = "<div>" + result + "</div>";
}
</script>
</html>
And the Code.gs would be like:
function nameSearch(firstName, lastName){
try {
var inputSheet = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1z3j7wxMLsXilyKDIH7XnE7VNQqF66fIH4B-mmuWwCJ8/edit#gid=1235654559");
var inputData = inputSheet.getDataRange().getValues();
for (var i = 1; i < inputData.length; i++) {
if (inputData[i][10] == firstName && inputData[i][11] == lastName) {
var result = inputData[i][14] + ": " + inputData[i][15];
return result;
}
}
} catch(e) {
alert(e)
}
}
function doGet(e) {
return HtmlService.createHtmlOutputFromFile("your-html-name");
}
I'm not sure you want to write the result to the HTML, but in any case, at this point it shouldn't be difficult to modify this so that it writes exactly what you want and where you want.
Reference:
google.script.run.myFunction(...) (any server-side function)
withSuccessHandler(function)
I hope this is of any help.
Try this:
Launch the dialog fill the text boxes and click submit. The view logs and see the next dialog.
function launchADialog() {
var html='<form><br /><input type="text" name="Name" /> Name: <br /><input type="text" name="Age" /> Age: <br />';
html+='<select name="Children" ><option value="0">None</option><option value="1">One</option><option value="2">Two</option></select> Children:<br />';
html+='<input type="button" value="Submit" onClick="google.script.run.processForm(this.parentNode);" /></form>';
var userInterface=HtmlService.createHtmlOutput(html);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "The Form");
}
function processForm(form) {
Logger.log(JSON.stringify(form));
var s=Utilities.formatString('<br />Name: %s <br />Age:%s <br />Number Of Children: %s', form.Name, form.Age, form.Children);
s+='<br /><input type="button" value="Close" onClick="google.script.host.close();" />';
var userInterface=HtmlService.createHtmlOutput(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, "Form Data")
}
If one of the identified DOM elements is empty, change the background color to red, if not, change to transparent. Why does this not work on the phone or position fields?
I have another script targeting elements like document.forms["pledge"]["position"] which also works on all other fields but phone and position. What am I missing?
function checkFilled() {
var fname = document.getElementById("fname"),
lname = document.getElementById("lname"),
email = document.getElementById("email"),
country = document.getElementById("country"),
zip = document.getElementById("zip"),
position = document.getElementById("position"),
phone = document.getElementById("phone");
;
if (fname.value != "") {
fname.style.backgroundColor = "transparent";
} else {
fname.style.backgroundColor = "red";
}
if (lname.value != "") {
lname.style.backgroundColor = "transparent";
} else {
lname.style.backgroundColor = "red";
}
if (email.value != "") {
email.style.backgroundColor = "transparent";
} else {
email.style.backgroundColor = "red";
}
if (country.value != "") {
country.style.backgroundColor = "transparent";
} else {
country.style.backgroundColor = "red";
}
if (zip != undefined && zip.value != "") {
zip.style.backgroundColor = "transparent";
} else {
zip.style.backgroundColor = "red";
}
if (position.value != "") {
position.style.backgroundColor = "transparent";
} else {
position.style.backgroundColor = "red";
}
if (phone.value != "") {
phone.style.backgroundColor = "transparent";
} else {
phone.style.backgroundColor = "red";
}
}
HTML
<form name="pledge" id="form">
<input class="input" type="text" id="fname" name="first_name" placeholder="First Name" onchange="checkFilled()">
<input class="input" type="text" id="lname" name="last_name" placeholder="Last Name" onchange="checkFilled()">
<input class="input" type="text" id="position" name="user_position" placeholder="Position in Government" onchange="checkFilled()">
<input class="input" type="text" id="country" name="user_country" placeholder="Country" onchange="checkFilled()">
<input class="input" type="email" id="email" name="user_email" placeholder="Official Government Email" onchange="checkFilled()">
<input class="input" type="number" id="phone" name="user_phone" placeholder="Office Phone Number" onchange="checkFilled()">
<input class="input full-width" type="submit" value="Take The Pledge!">
</form>
https://codepen.io/froggomad/pen/maRJxr
The script was failing because it was trying to handle the zip element which doesn't exist on this form. I mistakenly tried to handle that condition by checking to see if it existed and contained a value and then changing its background color if both conditions weren't true (OOPS)
Working Code
if (zip != undefined) {
if (zip.value != "") {
zip.style.backgroundColor = "transparent";
} else {
zip.style.backgroundColor = "red";
}
}
Your form does not have an element with the zip id and is therefore throwing errors trying to modify the zip style property in the else statement of your zip check since it is null. Since that error causes the function to fail, the position and phone based if statements don't execute.
If you remove the if/else block checking the zip variable, both of those fields work again.
I need to validate my form using JavaScript because iPhone / Safari do not recognize the required attribute. I want individual error messages to appear below each empty input field.
My code works, but the individual error message does not disappear when the field is filled in. Also, I would like all messages to appear initially, for all empty fields (not one by one). I am very very new to JavaScript, sorry.
My HTML:
<form onsubmit="return validateForm()" method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
And my JavaScript:
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else {return true;}
}
</script>
Thanks for your help.
Here is a solution that displays all relevant errors when the form is first submitted, and removes an error when the user modifies text in the relevant input element.
To get it to display all of the errors on first run, I used if statements instead of if else, and used a flag to determine whether the form should be submitted. To remove the warnings when the input is modified, I bound the onkeyup events of the inputs.
I ended up removing the required attributes on the inputs so that the demonstration will work in a modern browser that supports them.
Live Demo:
document.getElementById("english_registration_form").onsubmit = function () {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
var submit = true;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").innerHTML = nameError;
submit = false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").innerHTML = emailError;
submit = false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").innerHTML = telephoneError;
submit = false;
}
return submit;
}
function removeWarning() {
document.getElementById(this.id + "_error").innerHTML = "";
}
document.getElementById("name").onkeyup = removeWarning;
document.getElementById("email").onkeyup = removeWarning;
document.getElementById("telephone").onkeyup = removeWarning;
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" placeholder="Name"> <span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" placeholder="Email"> <span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" placeholder="Telephone"> <span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
JSFiddle Version: https://jsfiddle.net/xga2shec/
First of all, we change your function validateForm so it can handle multiple validations.
Then, we create a DOMContentLoaded event handler on the document, and we call the validateForm function, so we validate the field when the page is loaded.
And to finish, we create input event handlers on the inputs, so everytime someone change any data inside them, the form is validated again.
Take a look at the code commented, and see the working version in action!
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
you have to use style.display="none" to hide error
and style.display="block" to show error
<script>
function validateForm() {
var x = document.forms["english_registration_form"]["name"].value;
var y = document.forms["english_registration_form"]["email"].value;
var z = document.forms["english_registration_form"]["telephone"].value;
if (x == null || x == "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="block";
document.getElementById("name_error").innerHTML = nameError;
return false;
}
else if (x != null || x != "") {
nameError = "Please enter your name";
document.getElementById("name_error").style.display="none";
return false;
}
if (y == null || y == "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="block";
document.getElementById("email_error").innerHTML = emailError;
return false;
}
else if (y != null || y != "") {
emailError = "Please enter your email";
document.getElementById("email_error").style.display="none";
return false;
}
if (z == null || z == "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="block";
document.getElementById("telephone_error").innerHTML = telephoneError;
return false;
}
else if (z != null || z != "") {
telephoneError = "Please enter your telephone";
document.getElementById("telephone_error").style.display="none";
return false;
}
else {return true;}
}
</script>
function validateForm() {
var valid = true; // creates a boolean variable to return if the form's valid
if (!validateField(this, 'name')) // validates the name
valid = false;
if (!validateField(this, 'email')) // validates the email (look that we're not using else if)
valid = false;
if (!validateField(this, 'telephone')) // validates the telephone
valid = false;
return valid; // if all the fields are valid, this variable will be true
}
function validateField(context, fieldName) { // function to dynamically validates a field by its name
var field = document.forms['english_registration_form'][fieldName], // gets the field
msg = 'Please enter your ' + fieldName, // dynamic message
errorField = document.getElementById(fieldName + '_error'); // gets the error field
console.log(context);
// if the context is the form, it's because the Register Now button was clicked, if not, check the caller
if (context instanceof HTMLFormElement || context.id === fieldName)
errorField.innerHTML = (field.value === '') ? msg : '';
return field.value !== ''; // return if the field is fulfilled
}
document.addEventListener('DOMContentLoaded', function() { // when the DOM is ready
// add event handlers when changing the fields' value
document.getElementById('name').addEventListener('input', validateForm);
document.getElementById('email').addEventListener('input', validateForm);
document.getElementById('telephone').addEventListener('input', validateForm);
// add the event handler for the submit event
document.getElementById('english_registration_form').addEventListener('submit', validateForm);
});
<form method="post" action="form.php" name="english_registration_form" id="english_registration_form">
<input type="text" id="name" name="name" aria-describedby="name-format" required placeholder="Name">
<span class="error"><p id="name_error"></p></span>
<input type="email" id="email" name="email" required placeholder="Email">
<span class="error"><p id="email_error"></p></span>
<input type="tel" id="telephone" name="telephone" required placeholder="Telephone">
<span class="error"><p id="telephone_error"></p></span>
<button class="register_button" type="submit" value="submit">Register Now</button>
</form>
js validation works perfectly when I step through it, but fails at "normal speed." SPECIFICALLY: if a dup email is caught but the other fields are filled in correctly, the form can be submitted (but no error is forthcoming when stepping through the code). Has anyone seen this before? I know I could just code it a different way, but I cannot simply walk away from this simple problem that's even become a bottle kneck without first understanding why this isn't working.
My approach is to validate onblur and onsubmit. I am using the jquery selector only for convenience and then again for an ajax call, but otherwise i'm using js. I am doing a loop through the fields but only operating on text and password fields.
checking for blanks
checking for no numbers in name
checking for email address properly formatted
and then checking for unique email in the email field
annotated code below for js and form below:
//registration validation
$('.validate').blur(function() {
var theForm = document.registerNewUserForm;
//removes error messages from html before the run
clearAllErrors(theForm);
var msg = "";
var mdiv;
theForm.submit.disabled=true;
document.getElementById("submitButton").disabled = true;
for (var i = 0; i < theForm.elements.length; i++) {
//mdiv is set to form element being evaluated at the time
mdiv = document.getElementById(theForm.elements[i].name + "Message");
msg = validateField(theForm.elements[i]);
if(msg != "") {
mdiv.innerHTML = msg;
break;
}
}
if(msg == "") {
theForm.submit.disabled=false;
document.getElementById("submitButton").disabled = false;
}
});
$('#registerNewUserForm').submit(function() {
var theForm = document.registerNewUserForm;
clearAllErrors(theForm);
var msg = "";
var mdiv;
for (var i = 0; i < theForm.elements.length; i++) {
//mdiv is set to form element being evaluated at the time
mdiv = document.getElementById(theForm.elements[i].name + "Message");
msg = validateField(theForm.elements[i]);
if(msg != "") {
break;
}
}
if (msg != ""){
mdiv.innerHTML = msg;
return false;
} else {
theForm.submit();
}
});
function validateField(theField) {
msg = "";
//all fields are required
if (theField.type == "text" || theField.type == "password") {
if (theField.value == "") {
msg = "The " + theField.name + " field is required.";
}
}
//name fields are non-numeric
if (theField.name == "fullName"){
if (hasNumber(theField.value) == true){
msg= "The Name field is non-numeric.";
}
}
//email must be correctly formatted
if (theField.name == "email") {
msg = emailCheck (theField.value);
if (msg == "") {
//email address must also be unique
chkEmail();
msg = document.getElementById('emailMessage').innerHTML;
}
}
return msg;
}
function chkEmail() {
emailAddr = document.getElementById("email").value;
$.ajax({
url: '/chkEmail',
type: 'POST',
data: 'emailAddr=' + encodeURIComponent(emailAddr),
dataType: "xml",
context: document.body,
success: function(data) {
document.getElementById('emailMessage').innerHTML = $(data).find("message").text();
}
});
}
<form name="registerNewUserForm" id="registerNewUserForm" action="/register" method="post">
<br/>
<div>Create an Account and join the fun!</div>
<div><input class="validate" type="text" id="fullName" required placeholder="Full Name" name="fullName" value="" size="30"></div>
<div id="fullNameMessage" class="error"></div>
<div><input class="validate" type="text" id="email" required placeholder="Email Address" name="email" value="" size="30"></div>
<div id="emailMessage" class="error"></div>
<div><input class="validate" type="password" id="passWord" required placeholder="Password" name="passWord" value="" size="30"></div>
<div id="passWordMessage" class="error"></div>
<div style="position:relative;left:173px;"><input id="submitButton" type="submit" value="Signup for PastelPlanet"></div>
<input type="hidden" name="formName" value="registerNewUserForm">
<input type="hidden" name="urlDestination" value="">
</form>
Your "chkEmail" function involves a call to the server, and it's asynchronous. The call to the server will not be complete when the function returns, when you're running at "full speed".