js forms clearing after validate - javascript

Hi i am wondering if there is any way of stopping my forms from clearing after I submit and the validation error comes up?
Just to clarify I have multiple forms, when user submits I am using js to validate, when the validation error alerts all the forms reset is there any way to stop that??? "yes it does have to be javascript"
<script>
//calender dropdown menu
var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
function populatedropdown(dayfield, monthfield, yearfield,init){
var dayfield=document.getElementById(dayfield);
var monthfield=document.getElementById(monthfield);
var yearfield=document.getElementById(yearfield);
var today=(init)?new Date():new Date(yearfield.value*1,monthfield.value*1)
dayfield.options.length=0;
for (var i=0; i<new Date(today.getFullYear(),today.getMonth()+1,-1).getDate(); i++) dayfield.options[i]=new Option(i+1,i+1)
dayfield.selectedIndex=(init)?today.getDate()-1:0; //select today's day
if (init){
for (var m=0; m<12; m++) monthfield.options[m]=new Option(monthtext[m],m);
}
monthfield.selectedIndex=(init)?today.getMonth():0; //select today's day
if (init){
var thisyear=today.getFullYear()
for (var y=0; y<20; y++) yearfield.options[y]=new Option(thisyear, thisyear++)
}
}
// function validate
function validate_form ()
{
valid = true;
// validate name
if ( document.input.name.value == "" )
{
alert ( "Please enter your name" );
valid = false;
}
// validate address
if ( document.input.address.value == "" )
{
alert ( "Please enter your address address" );
valid = false;
}
// validate suburb town
if ( document.input.town.value == "" )
{
alert ( "Please enter your Suburb or town" );
valid = false;
}
// validate postcode
var y = document.getElementById('postcode').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Postcode must be in numbers.");
document.getElementById('postcode').focus();
return false;
}
if (y.length>4 || y.length<4)
{
alert("Postcode should be 4 digit");
document.getElementById('postcode').focus();
return false;
}
// validate home phone
var y = document.getElementById('hphone').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Home Phone number must be in numbers.");
document.getElementById('hphone').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Home Phone number should be 10 digit");
document.getElementById('hphone').focus();
return false;
}
// validate work phone
var y = document.getElementById('wphone').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("work Phone number must be in numbers.");
document.getElementById('wphone').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Work Phone number should be 10 digit");
document.getElementById('wphone').focus();
return false;
}
// validate fax
var y = document.getElementById('fax').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Fax number must be in numbers.");
document.getElementById('fax').focus();
return false;
}
if (y.length>10 || y.length<10)
{
alert("Fax Phone number should be 10 digit");
document.getElementById('fax').focus();
return false;
}
// validate email
{
var x=document.forms["input"]["email"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
}
{
// validate radio buttons
var o = document.getElementById('1');
var t = document.getElementById('2');
if ( (o.checked == false ) && (t.checked == true ) )
{
// validate alternative address
if ( document.input.street.value == "" )
{
alert ( "Please enter alternative address address" );
valid = false;
}
// validate suburb town
if ( document.input.suburb.value == "" )
{
alert ( "Please enter alternative Suburb or town" );
valid = false;
}
// validate postcode
var y = document.getElementById('postcode2').value;
if(isNaN(y)||y.indexOf(" ")!=-1)
{
alert("Postcode must be in numbers.");
document.getElementById('postcode2').focus();
return false;
}
if (y.length>4 || y.length<4)
{
alert("Alternative Postcode should be 4 digit");
document.getElementById('postcode2').focus();
return false;
}
// validate message box
var o = document.getElementById('card');
if ( (o.checked == true ))
{
if ( document.input.message.value == "" )
{
alert ( "Please enter message" );
valid = false;
}
return valid;
}
}
}
}
</script>
<input type="submit" value="Submit" />

ID values should not begin with numbers.
Here is a short example of capturing and affecting the outcome of a form submission.
One of the most common mistakes is forgetting to return the value of the onsubmit function.
Without a complete example, preferrably a fiddle, it isn't easy to know precisely what's wrong.

Related

Form validation using javascript (Registration Form with formatting)

I am trying to validate each field and display appropriate error messages using defined formatting. The username displayed appropriate error message, but the rest of the code is not "working". The email field was working, but after I store the variables atEmail and dotEmail, it didn't work anymore. I have been trying at this for a couple of days already. Any suggestions is greatly appreciated.
function validateForm() {
var firstPassword = document.myForm.passwordOne.value;
var secondPassword = document.myForm.passwordTwo.value;
var emailID = document.myForm.email.value;
var alphaNumeric = /^[\w ]+$/;
var letters = /^[A-Za-z]+$/;
var atEmail = emailID.indexOf("#");
var dotEmail = emailID.lastIndexOf(".");
var phone = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(!alphaNumeric.test(document.myForm.userName.value)) {
alert( "Please enter letters and numbers only!" );
document.myForm.userName.focus() ;
return false;
}
if(firstPassword.value.length < 8) {
alert( "Password must be at least 8 characters" );
document.myForm.passwordOne.focus() ;
return false;
}
if(document.myForm.firstPassword.value != document.myForm.secondPassword.value ) {
alert( "Password must match!" );
document.myForm.passwordTwo.focus() ;
return false;
}
if(!letters.match(document.myForm.firstName.value)) {
alert( "Your first name should only contain letters!" );
document.myForm.firstName.focus() ;
return false;
}
if(!letters.match(document.myForm.lastName.value)) {
alert( "Your last name should only contain letters!" );
document.myForm.lastName.focus() ;
return false;
}
if (atEmail < 1 || ( dotEmail - atEmail < 2 )) {
alert("Please enter valid email address format: xxx#xxx.xxx");
document.myForm.email.focus() ;
return false;
}
if(phonenumber.value.match(phone)) {
alert( "Please enter valid phone number format:(xxx) xxx-xxxx" );
document.myForm.phonenumber.focus() ;
return false;
}
if((document.myForm.signUpNewletter[0].checked == false) &&(document.myForm.signUpNewletter[1].checked == false )) {
alert( "Please check yes or no!" );
document.myForm.signUpNewsletter.focus() ;
return false;
}
return true;
}
Are you sure this is correct?
if(document.myForm.firstPassword.value != document.myForm.secondPassword.value ) {
You have already defined firstPassword and secondPassword variables, then why use them in document.myForm.firstPassword and document.myForm.secondPassword

Javascript Validation not working (onSubmit)

Vaidation function called on submit.
HTML
<input type="submit" class="submit" value="submit">
JS
window.load = function() {
var form = document.getElementById('form');
form.onsubmit = function(e) {
return validate(); // will be false if the form is invalid
}
}
Validate()
function validate() {
var x = document.forms["form"]["fname"].value;
var y = document.forms["form"]["pname"].value;
var email = document.forms["form"]["email"].value;
var phone = document.forms["form"]["phone"].value;
var date = document.forms["form"]["date"].value;
var month = document.forms["form"]["month"].value;
var year = document.forms["form"]["year"].value;
return false;
alert('wass');
if (x==null || x == "" || isNaN(x) == false) {
alert("Check Name, It can't have numbers. You can use Roman numbers.");
return false;}
else if (y == null || y == "") {
alert("Picture Name must be filled out");
return false;
}
else if(email == '' || email.indexOf('#') == -1 || email.indexOf('.') == -1)
{
alert("Insert valid Email Address");
return false;
}
else if(phone == ''|| phone <1000000000 || phone >9999999999){
alert("Enter valid phone number");
return false;
}else if(date =='' || date<01 || date >31){
alert("Enter valid Date ");
return false;
}else if(month =='' || month<1 || month >12){
alert("Enter valid Month ");
return false;
}else if(year =='' || year<1800 || year >2016){
alert("Enter valid Year ");
return false;
}
//Function used to make colors red instead of individual codelines
function makeRed(inputDiv){
inputDiv.style.backgroundColor="#AA0000";
//inputDiv.parentNode.style.backgroundColor="#AA0000";
//inputDiv.parentNode.style.color="#FFFFFF";
}
//Function made to clean the divs when the validation is met.
function makeClean(inputDiv){
inputDiv.style.backgroundColor="#FFFFFF";
inputDiv.parentNode.style.backgroundColor="#FFFFFF";
inputDiv.parentNode.style.color="#000000";
}
}
Form still gets submitted. Possible issues?
You'll need to prevent the default form submission using:
e.preventDefault();
Place this above your validate function.
Then use the submit() function on the form to actually submit the form provided your validation passes.
At the minute your form is submitting regardless.
You need to prevent default functionality of form submit, by calling e.preventDefault(). In your case:
window.load = function () {
document.getElementById('form').onsubmit = function (e) {
if (!validate()) {
e.preventDefault();
}
}
}

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.

HTML Form Validation Infinite Loop using an array of Functions

I am getting an infinite loop when pressing submit after filling in 3 / 7 of the form fields. I fill in the first and last name, and the email address.
Here is the function that I suspect the infinite loop is coming from:
function runValidation()
{
// Element Variables
var name_first = document.forms[0].elements["name_first"];
var name_last = document.forms[0].elements["name_last"];
var address_email = document.forms[0].elements["address_email"];
var address_number = document.forms[0].elements["address_number"];
var address_postal = document.forms[0].elements["address_postal"];
var url_link = document.forms[0].elements["other_website"];
var user_age = document.forms[0].elements["other_age"];
// Arrays of elements and functions
var userVariables = new Array(name_first, name_last, address_email, address_number, address_postal, url_link, user_age);
var userFunctions = new Array(valName, valName, valEmail, valNum, valCode, valLink, valAge);
var userFuncExec = new Array();
for (i = 0; i < userVariables.length - 1; i++)
{
userFuncExec[i] = userFunctions[i](userVariables[i]);
if ( userFuncExec[i] == false )
{
userVariables[i].value = "";
userVariables[i].focus();
return false;
}
}
// If the function has not returned false , then the form is valid;
document.forms[0].submit();
}
Here is the entire .js file:
http://pastie.org/5563532
// This is the validation for the contact form of Exquisite Taste
var debugOn = true; // toggles debug alerts.
function runValidation()
{
// Element Variables
var name_first = document.forms[0].elements["name_first"];
var name_last = document.forms[0].elements["name_last"];
var address_email = document.forms[0].elements["address_email"];
var address_number = document.forms[0].elements["address_number"];
var address_postal = document.forms[0].elements["address_postal"];
var url_link = document.forms[0].elements["other_website"];
var user_age = document.forms[0].elements["other_age"];
// Arrays of elements and functions
var userVariables = new Array(name_first, name_last, address_email, address_number, address_postal, url_link, user_age);
var userFunctions = new Array(valName, valName, valEmail, valNum, valCode, valLink, valAge);
var userFuncExec = new Array();
for (i = 0; i < userVariables.length - 1; i++)
{
userFuncExec[i] = userFunctions[i](userVariables[i]);
if ( userFuncExec[i] == false )
{
userVariables[i].value = "";
userVariables[i].focus();
return false;
}
}
// If the function has not returned false , then the form is valid;
document.forms[0].submit();
}
function valName(nam)
{
// This validates whatever name is passed.
if(nam.value.length > 1)
{
if(debugOn)
alert("Name is valid");
return true;
}else{
alert("Please enter a name that is at least 2 characters long.");
return false;
}
}
function valEmail(email)
{
// This function checks to see if the email address entered is valid.
// Check if the email field is less than 10 characters ( 3#3.2-3 = 10 - 11 characters for the shortest email address)
if ( email.value.length < 10 )
{
alert("Your email is too short to be valid.")
return false;
}
// Check to see the email has at least one period and one # symbol
if ( email.value.indexOf(".") < 0 || email.value.indexOf("#") < 0)
{
alert("The format of your email is invalid. All emails require a '.' and a '#'");
return false;
}
// Check if the last index of the '.' is after the '#' symbol & make sure there is only one index of '#'
if ( email.value.lastIndexOf(".") < email.value.indexOf("#") || email.value.indexOf("#") != email.value.lastIndexOf("#") )
{
alert("Your email is invalid and may have too many # symbols or have them in the wrong place");
return false;
}
// Check to see that the index of the last '.' has at least two characters after it.
if ( email.value.lastIndexOf(".") > email.value.length-3 )
{
alert("Your top level domain has to be at least 2 characters");
return false;
}
// Check to see if the split array has at least 3 characters in each section except for the last (TLD).
var email_attributes = new Array();
var email_attributes = email.value.split("."); // tiessen-b#webmail.uwinnipeg.ca
for ( i = 0; i < email_attributes.length - 2; i++ ) // -2 = (-1 so length = index; and -1 so the last section isn't included.)
{
// If one of the characters in the array value is '#' and the string length is < 3 then it isn't long enough.
if ( email_attributes[i].indexOf("#") > -1 )
{
// If the length of the string - 1 (for the '#') symbol is not considered a valid symbol.
if ( ( email_attributes[i].length - 1 ) < 3 )
{
alert("Your email doesn't have a long enough section");
return false;
}
}
}
// If it got this far it is probably a valid email address.
alert("Your email is valid!");
return true;
}
function valNum(num)
{
// This function validates a 10 or 12 digit phone number
var isNum = /[0-9]/; // If the value is a number
// Check to see if the number length is either 10 or 12
if ( num.value.length == 10 || num.value.length == 12)
{
// Make sure every character is a number.
for (i = 0; i < num.value.length; i++)
{
if ( !isNum.test( num.value.charAt(i) ) )
{
alert("You have entered an invalid number.");
return false;
}
}
}
else if ( num.value.length == 12 )
{
// split all numbers into an array with a delimiter of '-'
var numbers = num.value.split("-");
// check if the array length is not 3 or has 4 digits in the last section
if ( numbers.length != 3 || numbers[0].length > 3 || numbers[1].length > 3 );
{
alert("Your number is not formatted correctly. Make sure it is formatted like this: 204-290-9611.");
return false;
}
// loop through each section of the numbers array and make sure they are all numbers
for ( l = 0; l < numbers.length - 1; l++ )
{
for ( i = 0; i < numbers[l].length; i++)
{
if ( !isNum.test(numbers[l].charAt(i)) )
{
alert("Your phone number has invalid characters");
return false;
}
}
}
}else{
alert("Phone number is invalid");
return false;
}
if(debugOn)
alert("Phone number is invalid");
return true;
}
function valCode(code)
{
// This function validates a postal code.
var valid = true;
var isChar = /[A-z]/;
var isNum = /[0-9]/;
// Make sure the postal code is 6 characters long.
if( code.value.length != 6)
{
alert("Please enter a 6 digit/character postal code");
return false;
}else{
if ( !isChar.test( code.value.charAt(0) ) )
valid = false;
if ( !isNum.test( code.value.charAt(1) ) )
valid = false;
if ( !isChar.test( code.value.charAt(2) ) )
valid = false;
if ( !isNum.test( code.value.charAt(3) ) )
valid = false;
if ( !isChar.test( code.value.charAt(4) ) )
valid = false;
if ( !isNum.test( code.value.charAt(5) ) )
valid = false;
if (valid)
{
if(debugOn)
alert("Postal Code is valid");
return true;
}else{
alert("Your Postal Code is formatted incorrectly.");
return false;
}
}
}
function valLink(link)
{
if(link.value.length > 0)
{
linkParts = link.value.split(".");
if ( linkParts[0] == "www" || linkParts[0] == "http://www")
{
if( linkParts[linkParts.length-1].length < 2 || linkParts.length < 3)
{
alert("Invalid domain");
focusEmpty(link);
}else{
return true;
}
}else{
alert("invalid host");
focusEmpty(link);
}
}else{
return true;
}
}
function valAge(age)
{
// This function validates the users age.
var parsedAge = parseInt(age.value, 10);
if( age.value.length > 0 )
{
if( isNaN(parsedAge) )
{
alert("invalid age");
focusEmpty(age);
}else{
if(age.value < 1 || age.value > 125)
{
alert("Is that your real age? Please try again...");
focusEmpty(age);
}else{
return true;
}
}
}else{
// If the user doesn't submit anything return true and validate (Age is optional).
if(debugOn)
alert("Age is empty but valid.");
return true;
}
}
Here is the code for the HTML form:
<form method="post" enctype="text/plain" action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi" name="contactForm">
<div>
<p>First Name:</p>
<input name="name_first" type="text" />
</div>
<div>
<p>Last Name:</p>
<input name="name_last" type="text" />
</div>
<div>
<p>Email Address:</p>
<input name="address_email" type="text" />
</div>
<div>
<p>Phone Number:</p>
<input name="address_number" type="text" />
</div>
<div>
<p>Postal Code:</p>
<input name="address_postal" type="text" />
</div>
<div>
<p>Website:</p>
<input name="other_website" type="text" />
</div>
<div>
<p>Age:</p>
<input name="other_age" type="text" />
</div>
<div style="text-align:right; margin-right:20px;">
<input name="submit" type="button" value="Send" onclick="runValidation();"/>
</div>
</form>
Why am I getting an infinite loop?
Use for (var i = 0;... in your loop definitions rather than for (i = 0.
Variable scope in javascript can be tricky to understand. The answer to What is the scope of variables in JavaScript? has a great explanation.

Calling a regular expression in a javascript function

I've spent many hours trying to work this out. I know it's something easy but it just will not work for me!
I would like to validate for a password using this expression ^.*(?=.{6,})(?=.*[a-zA-Z])[a-zA-Z0-9]+$ with javascript.
I'm not sure how to structure the function and how to call it in the code. I've got something working for validating the email but I can't make the password expression work.
function validateEmail()
{
var emailID = document.myForm.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email address")
document.myForm.email.focus() ;
return false;
}
return( true );
}
function validate()
{
if( document.myForm.email.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.email.focus() ;
return false;
}
else
{
// Put extra check for data format
var ret = validateEmail();
if( ret == false )
{
return false;
}
}
I would like to call the passwordChecker from the validate function.
This should do
function validateEmail()
{
var emailID = document.myForm.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email address")
document.myForm.email.focus() ;
return false;
}
return true;
}
function validatePassword()
{
var reg = /^.*(?=.{6,})(?=.*[a-zA-Z])[a-zA-Z0-9]+$/;
return reg.test(document.myForm.password.value);
}
function validate()
{
if(document.myForm.email.value == "" || !validateEmail())
{
alert( "Please provide a valid Email!" );
document.myForm.email.focus() ;
return false;
}
else if(!validatePassword())
{
alert("Please provide a valid password!");
document.myForm.password.focus() ;
return false;
}
return true;
}
My suggestion
function isEmail(email) {
var re = /^.*(?=.{6,})(?=.*[a-zA-Z])[a-zA-Z0-9]+$/;
return re.test(email);
}
function validate() {
var email = document.myForm.email;
if (email.value.trim() =="") { // may need IE support
alert( "Please provide your Email!" );
email.focus() ;
return false;
}
if (!isEmail(email.value)) {
alert( "Please provide a valid Email!" );
email.focus() ;
return false;
}
return true;
}

Categories

Resources