can't submit form after validation in javascript [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
Help, I am trying to validate my form. It can validate all fields, but not submitting after validated. I tried to run the codes in http://jsfiddle.net/CrLsR/297/ but after validated the form, it can't proceed to the test.html page. I'm new in javascript so, I can't figure out what is the probleml. Any help will very much appreciated. thanks..
here is the code :
//HTML FORM
<form name="form" id="form" onsubmit="return (validateForm(this));" action="test.htm" method="post">
<label for="firstname" id="errfName">First Name</label>
<li><input name="firstname" type="text" onkeyup="return(validatefName(this));"> <span id="warnfName"></span></li>
<label for="username" id="errUser">Username</label>
<li><input name="username" type="text" onkeyup="return(validateUsername(this));"> <span id="warnUser"></span></li>
<label for="password" id="errPass">Password</label></li>
<li><input name="password" id="password" type="password" onkeyup="return(validatePassword(this));"> <span id="warnPass"></span></li>
<label for="password2" id="errPass2">Confirm Password</label></li>
<li><input name="password2" id="password2" type="password" onkeyup="return(validatePassword2(this));"> <span id="warnPass2"></span></li>
<label for="email" id="errEmail">Email Address</label>
<li><input name="email" type="text" onkeyup="return(validateEmail(this));"> <span id="warnEmail"></span></li>
<li> </td>
<li><input name="Submit" value="Send" type="submit" ></li>
// Javascript code
var borderErr = "1px solid rgb(100,0,50)";
var borderOk = "1px solid rgb(0,150,50)";
var warn = "<b class='warn'>!</b>";
// for First Name validation
var matchfName = /^[a-zA-Z]$/;
var errorfNameEmpty = "<b class='err'>First name is required";
// for Username validation
var matchUsername = /^[A-Za-z][A-Za-z0-9]*(?:_[A-Za-z0-9]+)*$/;
var matchUsername2 = /^[a-z0-9_-]{5,15}$/;
var errorUsernameEmpty = "<b class='err'>Username is required\n</b>";
var errorUsernameInvalid = "<b class='err'>The username is not valid. Must contains 5 to 15 alpha numeric characters\n</b>";
// for Password validation
var matchPass = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{7,15}$/;
var errPassEmpty = "<b class='err'>Password is required</b>";
var errPassInvalid = "<b class='err'>Password must contains with a combination of <br/>7 to 15 alpha numeric and special characters.";
// for Confirm Password validation
var errPassEmpty2 = "<b class='err'>Confirm password is required</b>";
var errPassInvalid2 = "<b class='err'>Confirm password must the same as password value.";
// for Email validation
var matchEmail = /^(([^<>()[\]\\.,;:\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,}))$/;
var errEmailEmpty = "<b class='err'>Email address is required</b>";
var errEmailInvalid = "<b class='err'>Invalid email address. Please enter a valid email.";
function validateForm(regForm) {
var warning = "";
warning += validatefName(regForm.firstname);
warning += validateUsername(regForm.username);
warning += validatePassword(regForm.password);
warning += validatePassword2(regForm.password2);
warning += validateEmail(regForm.email);
if (warning != "") {
return false;
}
return true;
}
// validate first name
function validatefName(fld) {
if(fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errfName").innerHTML=errorfNameEmpty;
document.getElementById("warnfName").innerHTML=warn;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errfName").innerHTML="First Name";
document.getElementById("warnfName").innerHTML="";
return true;
}
}
//validate username
function validateUsername(fld) {
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errUser").innerHTML=errorUsernameEmpty;
document.getElementById("warnUser").innerHTML=warn;
return false;
}
else if ((!matchUsername.test(fld.value)) || (!matchUsername2.test(fld.value))) {
fld.style.border=borderErr;
document.getElementById("errUser").innerHTML=errorUsernameInvalid;
document.getElementById("warnUser").innerHTML=warn;
return false;
}
else {
document.getElementById("errUser").innerHTML="Username";
document.getElementById("warnUser").innerHTML="";
fld.style.border=borderOk;
return true;
}
}
// validate password
function validatePassword(fld) {
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errPass").innerHTML=errPassEmpty;
document.getElementById("warnPass").innerHTML=warn;
return false;
}
else if (!matchPass.test(fld.value)) {
document.getElementById("errPass").innerHTML=errPassInvalid;
document.getElementById("warnPass").innerHTML=warn;
fld.style.border=borderErr;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errPass").innerHTML="Password";
document.getElementById("warnPass").innerHTML="";
return true;
}
}
// validate confirm password
function validatePassword2(fld) {
var passVal = document.getElementById("password").value;
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errPass2").innerHTML=errPassEmpty2;
document.getElementById("warnPass2").innerHTML=warn;
return false;
}
else if (passVal != fld.value) {
document.getElementById("errPass2").innerHTML=errPassInvalid2;
document.getElementById("warnPass2").innerHTML=warn;
fld.style.border=borderErr;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errPass2").innerHTML="Confirm Password";
document.getElementById("warnPass2").innerHTML="";
return true;
}
}
// validate email address
function validateEmail(fld) {
if (fld.value == "") {
fld.style.border=borderErr;
document.getElementById("errEmail").innerHTML=errEmailEmpty;
document.getElementById("warnEmail").innerHTML=warn;
return false;
}
else if (!matchEmail.test(fld.value)) {
fld.style.border=borderErr;
document.getElementById("errEmail").innerHTML=errEmailInvalid;
document.getElementById("warnEmail").innerHTML=warn;
return false;
}
else {
fld.style.border=borderOk;
document.getElementById("errEmail").innerHTML="Email Address";
document.getElementById("warnEmail").innerHTML="";
return true;
}
}

As your inner validation methods return true or false, you need to modify your parent validation method to this or similar.
function validateForm(regForm) {
var formValid = true;
formValid &= validatefName(regForm.firstname);
formValid &= validateUsername(regForm.username);
formValid &= validatePassword(regForm.password);
formValid &= validatePassword2(regForm.password2);
formValid &= validateEmail(regForm.email);
if (!formValid) {
return false;
}
return true;
}

Try changing this line
var warning = "";
warning += validatefName(regForm.firstname);
warning += validateUsername(regForm.username);
warning += validatePassword(regForm.password);
warning += validatePassword2(regForm.password2);
warning += validateEmail(regForm.email);
if (warning != "") {
To this line
if(validatefName(regForm.firstname) == true && validateUsername(regForm.username) == true && validatePassword(regForm.password) == true && validatePassword2(regForm.password2) == true && validateEmail(regForm.email) == true) {
and see if it is correct now

Based on your fiddle, I found some errors in your code in the condition
if (title=="" || title==null) { } else {
alert("Please enter only alphanumeric values for your advertisement title");
}
Should be
if (title.length != 0) { } else {
alert("Please enter only alphanumeric values for your advertisement title");
return false;
}
The second is a more effective way to check if a field has no value.
I've also added return false in your else condition and the last return should be true.
here is your validateForm function. I updated your fiddle here
function validateForm() {
// Validate Email
var email = $("#fremail").val();
if ((/(.+)#(.+){2,}\.(.+){2,}/.test(email)) || email.length != 0) {
} else {
alert("Please enter a valid email");
return false;
}
// Validate Title
var title = $("#frtitle").val();
if (title.length != 0) {} else {
alert("Please enter only alphanumeric values for your advertisement title");
return false;
}
// Validate URL
var url = $("#frurl").val();
if (validateURL(url)) {} else {
alert("Please enter a valid URL, remember including http://");
return false;
}
return true;
}

Set a Flag = 1 in the function validateForm()
Increment Flag, if have validation error
End, return true, if Flag == 1 which means no error
function validateForm()
{
var flag = 1;
// Validate URL
var url = $("#frurl").val();
if (validateURL(url)) { } else {
alert("Please enter a valid URL, remember including http://");
flag++;
}
// Validate Title
var title = $("#frtitle").val();
if (title=="" || title==null) { } else {
alert("Please enter only alphanumeric values for your advertisement title");
flag++;
}
// Validate Email
var email = $("#fremail").val();
if ((/(.+)#(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
alert("Please enter a valid email");
flag++;
}
if (flag == 1)
return true;
else
return false;
}

Related

Span tag becoming invisible after JavaScript function

I have tried to make a form but am having a problem where the second message in the span tag is disappearing after my JavaScript function is being run once the submit button is being pressed, and only the first message is being displayed.
function formValidate() {
var fname = document.getElementById('firstname').value;
if (fname == '' || fname == 'null') {
document.getElementById('fnamemessage').innerHTML = '* Please fill out first name';
return false;
}
var num = document.getElementById('mobilenumber').value;
if (isNaN(num)) {
document.getElementById('phonemessage').innerHTML = '* Please only enter numbers';
return false;
}
if (num == '' || num == 'null') {
document.getElementById('phonemessage').innerHTML = '* Please fill out mobile number';
return false;
}
if (num.length < 11) {
document.getElementById('phonemessage').innerHTML = '* Mobile number must be more than 10 digits';
return false;
}
if ((num.charAt(0) != 0) && (num.charAt(1) != 7)) {
document.getElementById('phonemessage').innerHTML = '* Mobile number must start with 07';
return false;
}
}
<form onsubmit='return formValidate()'>
First Name: <input type='text' id='firstname' value=''>
<span id='fnamemessage' class='messages'></span><br></br>
Mobile Number: <input type='text' id='mobilenumber' value=''>
<span id='phonemessage' class='messages'></span><br></br>
<input type='submit' value='Submit'>
</form>
It seems only the first message appears because the checks for the rest are not reached. You stop execution of the validate function as soon as the first error is reached. You can try to check all errors together as follows:
function formValidate() {
var valid = true;
var fname = document.getElementById('firstname').value;
if (fname=='' || fname==null) {
document.getElementById('fnamemessage').innerHTML='* Please fill out first name';
valid = false;
}
var num = document.getElementById('mobilenumber').value;
if(isNaN(num)) {
document.getElementById('phonemessage').innerHTML='* Please only enter numbers';
valid = false;
}
if (num=='' || num==null) {
document.getElementById('phonemessage').innerHTML='* Please fill out mobile number';
valid = false;
}
if (num.length<11) {
document.getElementById('phonemessage').innerHTML='* Mobile number must be more than 10 digits';
valid = false;
}
if((num.charAt(0)!=0) && (num.charAt(1)!=7)) {
document.getElementById('phonemessage').innerHTML='* Mobile number must start with 07';
valid = false;
}
return valid;
}
the problem is that you return false in an if-statement. If you return something (in this case false) it ends the functions. All other if-statements will NOT be executed. To fix this, just remove return false on each if-statement. Since the returned value will not be used you don't even need a return value.
The problem is that (since you don't stop the function and return false) the form will be submitted even if your validation rules don't match. In this case, you might want to try something like this:
function formValidate(event) {
var valid = true;
var fname = document.getElementById('firstname').value;
if (fname == '') {
document.getElementById('fnamemessage').innerHTML = '* Please fill out first name';
valid = false;
}
var num = document.getElementById('mobilenumber').value;
if (isNaN(num)) {
document.getElementById('phonemessage').innerHTML = '* Please only enter numbers';
valid = false;
}
if (num == '') {
document.getElementById('phonemessage').innerHTML = '* Please fill out mobile number';
valid = false;
}
if (num.length < 11) {
document.getElementById('phonemessage').innerHTML = '* Mobile number must be more than 10 digits';
valid = false;
}
if ((num.charAt(0) != 0) && (num.charAt(1) != 7)) {
document.getElementById('phonemessage').innerHTML = '* Mobile number must start with 07';
valid = false;
}
return valid;
}
<form onsubmit='return formValidate();'>
First Name: <input type='text' id='firstname' value=''>
<span id='fnamemessage' class='messages'></span><br></br>
Mobile Number: <input type='text' id='mobilenumber' value=''>
<span id='phonemessage' class='messages'></span><br></br>
<input type='submit' value='Submit'>
</form>
So you at the end you check if your form is valid and end the functions after ALL validations are done.

Clearing validation errors JavaScript

I have been attempting to clear messages once the user has successfully input completed the required validation rules, however I can't seem to clear all the validation errors, I did look around and tried what was suggested however it doesn't seem to have worked. I thought by placing empty innerHTML strings might work as I said it had been suggested within other posts
<form action ="" method="POST">
<span id="tryErr"></span><br>
<input type="text" id="username" placeholder="Username"><br>
<span id="usernameErr"></span><br>
<input type="text" id="email" placeholder="Email address"><br>
<span id="emailErr"></span><br>
<input type="password" id="password" placeholder="Password"><br>
<span id="passwordErr"></span><br>
<input type="submit" value="Submit" onclick=" return confirmValidation();">
</form>
JS
<script type="text/javascript">
function validateUsername(username, error){
var username = document.getElementById("username").value,
error = document.getElementById("usernameErr");
if(username == null || username==""){
return error.innerHTML = "Username is required";
return false;
}
else if(!username.match(/^[0-9a-z]+$/) || username.length < 3){
return error.innerHTML = "Username must be alphanumeric and three characters long";
return false;
}
else{
return error.innerHTML = "";
return true;
}
}
function validatePassword(password, error){
var password = document.getElementById("password").value,
error = document.getElementById("passwordErr");
if(password == null || password==""){
return error.innerHTML = "Password is required";
return false;
}
else if(password.length < 7){
return error.innerHTML = "Password must be seven characters long";
return false;
}
else{
return error.innerHTML = "";
return true;
}
}
function validateEmail(email, error){
var email = document.getElementById("email").value,
apos = email.indexOf("#"),
dotpos = email.lastIndexOf("."),
error = document.getElementById("emailErr");
if(email == null || email==""){
return error.innerHTML = "Email is required";
return false;
}
if (apos < 1 || dotpos-apos < 2 || dotpos == (email.length - 1)){
return error.innerHTML = "Please enter a valid email";
return false;
}
else{
return error.innerHTML = "";
return true;
}
}
function confirmValidation(e){
event.preventDefault(e);
if(!validateUsername()){
return false;
}
if(!validatePassword()){
return false;
}
if(!validateEmail()){
return false;
}
else{
//do something clever here
}
}
</script>
You should use onchange event on input types .
Like
<input type="text" id="username" placeholder="Username " onchange="validateUsername()">

Javascript Form Validation Not Successful

Practicing my Javascript on a simple HTML form. Enter password in one box, enter again to confirm in the second. Password should contain 6 character (including 1 number), and no spaces. An alert message should pop up if the passwords meet the criteria and match.
I have it mostly there, in that the error messages pop up if the criteria aren't met, but I can't get to alert "Success!" I've toyed with the if statements so many ways, I'm not sure what I'm missing. Any suggestions?
Javascript:
window.onload = function() {
document.getElementById('submit').addEventListener('click', validateInput);
}
var userPass = document.getElementById('password').value;
var confirmPass = document.getElementById('confirm_password').value;
function validatePassword() {
var userPass = document.getElementById('password').value;
if (userPass.length == 0) { // Nothing was entered
document.getElementById('password_error').innerHTML = 'Please enter a password';
} else if (userPass.length < 6) { // Less than 6 chars
document.getElementById('password_error').innerHTML = 'Your password must be at least 6 characters in length';
} else if (userPass.match(/\s/)) { // contains a space
document.getElementById('password_error').innerHTML = 'Your password cannot contain spaces';
} else if (!userPass.match(/\d/)) { // Does not contain a number
document.getElementById('password_error').innerHTML = 'Your password must contain a number';
} else if (userPass !== confirmPass) {
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
}
}
function validateConfirm() {
function clearFields (){
document.getElementById('password').value=null;
document.getElementById('confirm_password').value=null;
}
if (confirmPass.length == 0) {
document.getElementById('confirm_error').innerHTML = "Please confirm password to proceed";
} else if (confirmPass.length < 6) {
document.getElementById('confirm_error').innerHTML = "Your password must be at least 6 characters in length";
} else if (userPass !== confirmPass) {
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
}
}
function validateInput() {
validatePassword();
validateConfirm();
}
The form:
<form>
<fieldset>
<legend>CONFIRM PASSWORD</legend>
<label for="name">Password: </label>
<input type="text" id="password" size="10" />
<p id="password_error" class="error"></p>
<label for="name">Confirm Password: </label>
<input type="text" id="confirm_password" size="10" />
<p id="confirm_error" class="error"></p>
<button id="submit">Submit</button>
</fieldset>
</form>
I've found two fault in your code
Set clearFields() function outside function validatePassword();
var confirmPass enter inside function or pass from calling function
window.onload = function () {
document.getElementById('submit').addEventListener('click', validateInput);
}
function validatePassword() {
var userPass = document.getElementById('password').value;
var confirmPass = document.getElementById('confirm_password').value;
if (userPass.length == 0) { // Nothing was entered
document.getElementById('password_error').innerHTML = 'Please enter a password';
} else if (userPass.length < 6) { // Less than 6 chars
document.getElementById('password_error').innerHTML = 'Your password must be at least 6 characters in length';
} else if (userPass.match(/\s/)) { // contains a space
document.getElementById('password_error').innerHTML = 'Your password cannot contain spaces';
} else if (!userPass.match(/\d/)) { // Does not contain a number
document.getElementById('password_error').innerHTML = 'Your password must contain a number';
} else if (userPass !== confirmPass) {
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
}
}
function clearFields() {
document.getElementById('password').value = null;
document.getElementById('confirm_password').value = null;
}
function validateConfirm() {
var userPass = document.getElementById('password').value;
var confirmPass = document.getElementById('confirm_password').value;
if (confirmPass.length == 0) {
document.getElementById('confirm_error').innerHTML = "Please confirm password to proceed";
} else if (confirmPass.length < 6) {
document.getElementById('confirm_error').innerHTML = "Your password must be at least 6 characters in length";
} else if (userPass !== confirmPass) {
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
}
}
function validateInput() {
validatePassword();
validateConfirm();
}
<form>
<fieldset>
<legend>CONFIRM PASSWORD</legend>
<label for="name">Password: </label>
<input type="text" id="password" size="10" />
<p id="password_error" class="error"></p>
<label for="name">Confirm Password: </label>
<input type="text" id="confirm_password" size="10" />
<p id="confirm_error" class="error"></p>
<button id="submit">Submit</button>
</fieldset>
</form>
There are multiple issues
The function clearFields() is available only inside validateConfirm
You are reading the value of the confirm input only once at the page load, you need to read the new value within the validate method else it will always be empty string
Since you are validating the policy in the password field, not need to check it again for the confirm field since you are checking whether the confirm and password fields are the same
window.onload = function() {
document.getElementById('submit').addEventListener('click', validateInput);
}
function validatePassword() {
var userPass = document.getElementById('password').value;
var confirmPass = document.getElementById('confirm_password').value;
if (userPass.length == 0) { // Nothing was entered
document.getElementById('password_error').innerHTML = 'Please enter a password';
} else if (userPass.length < 6) { // Less than 6 chars
document.getElementById('password_error').innerHTML = 'Your password must be at least 6 characters in length';
} else if (userPass.match(/\s/)) { // contains a space
document.getElementById('password_error').innerHTML = 'Your password cannot contain spaces';
} else if (!userPass.match(/\d/)) { // Does not contain a number
document.getElementById('password_error').innerHTML = 'Your password must contain a number';
} else if (userPass !== confirmPass) {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = 'Passwords do not match. Please check again.';
} else {
document.getElementById('password_error').innerHTML = "";
document.getElementById('confirm_error').innerHTML = "";
alert("Success!");
clearFields();
return true;
}
return false;
}
function clearFields() {
document.getElementById('password').value = '';
document.getElementById('confirm_password').value = '';
}
function validateInput() {
return validatePassword();
}
<fieldset>
<legend>CONFIRM PASSWORD</legend>
<label for="name">Password:</label>
<input type="text" id="password" size="10" />
<p id="password_error" class="error"></p>
<label for="name">Confirm Password:</label>
<input type="text" id="confirm_password" size="10" />
<p id="confirm_error" class="error"></p>
<button id="submit">Submit</button>
</fieldset>

Javascript Email Validation from Form Field suddenly doesn't work?

Working on a web page which used to have a working email validation, but after adding in a few additional features it suddenly no longer works. The page shouldn't proceed unless all fields are valid, everything is basically client-side if you're wondering why it's a bit of a weird website.
Originally the e-mail validation worked for if the field was blank or did not have an '#' and '.' following it, using the code:
if (d==null || d=="")
{
document.forms["registration"]["email"].focus();
alert("Please enter your email address");
return false;
}
else
{
var emailAddress = d;
var atLoc = emailAddress.indexOf("#",1);
var dotLoc = emailAddress.indexOf(".",atLoc+2);
var len = emailAddress.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc+2)
{
return true;
}
else
{
alert("Invalid E-mail address format! Please enter your e-mail address again.");
document.forms["registration"]["email"].focus();
return false;
}
}
However, added with the entire code of:
function validateForm(){
{
var f=document.forms["registration"]["FirstName"].value;
var a=document.forms["registration"]["Surname"].value;
var b=document.forms["registration"]["address"].value;
var c=document.forms["registration"]["post"].value;
var d=document.forms["registration"]["email"].value;
var z=document.forms["registration"]["password"].value;
if (f==null || f=="")
{
document.forms["registration"]["FirstName"].focus();
alert("Please enter your first name");
return false;
}
if (a==null || a=="")
{
document.forms["registration"]["Surname"].focus();
alert("Please enter your surname");
return false;
}
if (b==null || b=="")
{
alert("Please enter your address");
document.forms["registration"]["address"].focus();
return false;
}
if (c==null || c=="")
{
alert("Please enter your postcode");
document.forms["registration"]["post"].focus();
return false;
}
if (d==null || d=="")
{
document.forms["registration"]["email"].focus();
alert("Please enter your email address");
return false;
}
else
{
var emailAddress = d;
var atLoc = emailAddress.indexOf("#",1);
var dotLoc = emailAddress.indexOf(".",atLoc+2);
var len = emailAddress.length;
if (atLoc > 0 && dotLoc > 0 && len > dotLoc+2)
{
return true;
}
else
{
alert("Invalid E-mail address format! Please enter your e-mail address again.");
document.forms["registration"]["email"].focus();
return false;
}
}
}
}
It no longer works...? Puzzled, any help appreciated.

Can't hide innerHTML after error corrected

Didn't see an answer so here goes. Error messages are using innerHTML. How do I get them to disappear once the error is corrected? Right now it just stays on. I tried resetting at the top of the script.
JSfiddle
HTML:
<form id="contact" name="contact" onsubmit="return validateFormOnSubmit(this)" action="" method="post">
<h2>Contact Me</h2>
<div id="main-error"></div>
<div>
<label>Name</label>
<input placeholder="First Name" type="text" name="name" id="name" tabindex="1" autofocus />
<div id="name-error"></div>
</div>
<div>
<label>Email</label>
<input placeholder="Email" type="email" name="email" id="email" tabindex="3" autofocus />
<div id="email-error"></div>
</div>
<div>
<label>Phone</label>
<input placeholder="Phone" type="text" name="phone" id="phone" tabindex="4" autofocus />
<div id="test"></div>
</div>
<div>
<button type="submit" name="submit" id="submit" tabindex="5">Send</button>
</div>
</form>
JS:
document.getElementById('name-error').innerHTML='';
document.getElementById('email-error').innerHTML='';
document.getElementById('phone-error').innerHTML='';
function validateFormOnSubmit(contact) {
var reason = "";
reason += validateEmail(contact.email);
reason += validatePhone(contact.phone);
reason += validateEmpty(contact.name);
if (reason != "") {
document.getElementById("main-error").innerHTML="Test main error message area";
return false;
}
return false;
}
// validate required fields
function validateEmpty(name) {
var error = "";
if (name.value.length == 0) {
name.style.background = 'Yellow';
document.getElementById('name-error').innerHTML="The required field has not been filled in";
} else {
name.style.background = 'White';
}
return error;
}
// validate email as required field and format
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error="";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (email.value == "") {
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter an email address.";
} else if (!emailFilter.test(temail)) { //test email for illegal characters
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter a valid email address.";
} else if (email.value.match(illegalChars)) {
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Email contains invalid characters.";
} else {
email.style.background = 'White';
}
return error;
}
// validate phone for required and format
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('test').innerHTML="Please enter a phone number";
phone.style.background = 'Yellow';
} else if (isNaN(parseInt(stripped))) {
document.getElementById('test').innerHTML="The phone number contains illegal characters.";
phone.style.background = 'Yellow';
} else if (!(stripped.length == 10)) {
document.getElementById('test').innerHTML="The phone number is too short.";
phone.style.background = 'Yellow';
}
return error;
}
thanks!
function validateFormOnSubmit(contact) {
reason = "";
reason += validateEmpty(contact.name);
reason+= validateEmail(contact.email);
reason+= validatePhone(contact.phone);
console.log(reason);
if ( reason.length>0 ) {
return false;
}
else {
return true;
}
}
// validate required fields
function validateEmpty(name) {
var error = "";
if (name.value.length == 0) {
name.style.background = 'Yellow';
document.getElementById('name-error').innerHTML="The required field has not been filled in";
var error = "1";
} else {
name.style.background = 'White';
document.getElementById('name-error').innerHTML='';
}
return error;
}
// validate email as required field and format
function trim(s)
{
return s.replace(/^\s+|\s+$/, '');
}
function validateEmail(email) {
var error="";
var temail = trim(email.value); // value of field with whitespace trimmed off
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (email.value == "") {
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter an email address.";
var error="2";
} else if (!emailFilter.test(temail)) { //test email for illegal characters
email.style.background = 'Yellow';
document.getElementById('email-error').innerHTML="Please enter a valid email address.";
var error="3";
} else if (email.value.match(illegalChars)) {
email.style.background = 'Yellow';
var error="4";
document.getElementById('email-error').innerHTML="Email contains invalid characters.";
} else {
email.style.background = 'White';
document.getElementById('email-error').innerHTML='';
}
return error;
}
// validate phone for required and format
function validatePhone(phone) {
var error = "";
var stripped = phone.value.replace(/[\(\)\.\-\ ]/g, '');
if (phone.value == "") {
document.getElementById('test').innerHTML="Please enter a phone number";
phone.style.background = 'Yellow';
var error = '6';
} else if (isNaN(parseInt(stripped))) {
var error="5";
document.getElementById('test').innerHTML="The phone number contains illegal characters.";
phone.style.background = 'Yellow';
} else if (stripped.length < 10) {
var error="6";
document.getElementById('test').innerHTML="The phone number is too short.";
phone.style.background = 'Yellow';
}
else {
phone.style.background = 'White';
document.getElementById('test').innerHTML='';
}
return error;
}
http://jsfiddle.net/tX5y5/59/
I have just changed place of inner html cleaning... and i have added some changes in whole validation (it didn't worked before properly).
You'll need to register a listener for when the user changes one of your input fields and run your validation function in the listener. Something like this:
document.getElementById('name').addEventListener("change", validateFormOnSubmit);
document.getElementById('email').addEventListener("change", validateFormOnSubmit);
document.getElementById('phone').addEventListener("change", validateFormOnSubmit);
If at all possible I'd recommend using an existing library for form validation (but you probably already knew that).

Categories

Resources