Form validation using javascript (Registration Form with formatting) - javascript

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

Related

Creating a pattern for a number which must be prefixed by 3 letters eg (IKA111111)

function validatetest(e)
{
debugger;
e.preventDefault();
// Declare all the variables here
var firstName = document.getElementById("firstName").value;
var lastName = document.getElementById("lastName").value;
var title = document.getElementById("title").value;
var healthNumber = document.getElementById("healthNumber").value);
var email = document.getElementById("email").value;
var telephoneNumber = parseInt(document.getElementById("telephoneNumber").value);
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
var validText = /^[a-zA-Z]*$/;
var validLastText = /^[a-zA-Z-]*$/;
var validEmail = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,6}$/;
//var n = healthNumber.startsWith("ZHA");
if(firstName!="" && lastName!= "" && title!="" && email !="")
{
if(email.match(validEmail))
{
if(!isNaN(telephoneNumber) && telephoneNumber >= 11111111111 && telephoneNumber <= 99999999999)
{
if(firstName.match(validText) && firstName.length >1)
{
if(lastName.match(validLastText) && lastName.length> 1)
{
if(healthNumber.match(validHealth))
{
alert("All information is Validated");
return true;
}
else
{
alert("error error");
return false;
}
}
else
{
document.getElementById("error4").innerHTML="letters and hypen only";
return false;
}
}
else
{
document.getElementById("error").innerHTML="letters only and more then one character";
return false;
}
}
else
{
document.getElementById("error2").innerHTML="Telephone number must be 11 num digits long";
}
}
else
{
document.getElementById("error3").innerHTML="email is not a valid format ";
return false;
}
}
else
{
alert("All fields must be entered except telephone Number ");
return false;
}
}
i am trying to create a validation process by using a pattern for a user inputted healthnumber so that it validates whether 3 letters are entered followed by 6 numbers via user input. (MIC123456 is example so MIC always has to been entered , those specific letters)
Not sure if my technique is correct by using a pattern stored in the ValidHeath variable as you can i have used this idea for my email validation etc .
You have an extra + in your regex, make it
var validHealth = /^[A-Z]{3}[0-9]{6}$/;
Demo
var isMatch = !!"IKA111111".match(/^[A-Z]{3}[0-9]{6}$/);
isMatch ? console.log( "Matching" ) : console.log( "Not Matching" );

I am having problems getting my form to validate or submit [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
My form does not seem to be validating or submitting. It was submitting and validating before, but the Jquery error messages were not all displaying at the same time so I had to edit the code, and now it is not submitting or validating at all.
Here is my JS:
function validateUserName(user)
{
var u = document.forms["NewUser"]["user"].value
var uLength = u.length;
var illegalChars = /\W/; // allow letters, numbers, and underscores
if (u == null || u == "")
{
return "You Left the Username field Emptyyy";
}
else if (uLength <4 || uLength > 11)
{
return "The Username must be between 4 and 11 characters";
}
else if (illegalChars.test(u))
{
return "The Username contains illegal charectors men!";
}
else
{
return "";
}
}
function validatePassword(pwd)
{
var p = document.forms["NewUser"]["pwd"].value
var cP = document.forms["NewUser"]["confirmPwd"].value
var pLength = p.length;
if (p == null || p == "")
{
return "You left the password field empty";
}
else if (pLength < 6 || pLength > 20)
{
return "Your password must be between 6 and 20 characters in length";
}
else if (p != cP)
{
return "The passwords do not match!"
}
else
{
return "";
}
}
function validateEmail(email)
{
var e = document.forms["NewUser"]["email"].value
var eLength = e.length;
var emailFilter = /^[^#]+#[^#.]+\.[^#]*\w\w$/ ;
var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
if (eLength == "" || eLength == null)
{
return "You left the email field blank!";
}
else if (e.match(illegalChars))
{
return "ILEGAL CHARECTORS DETECTED EXTERMINATE";
}
else
{
return "";
}
}
function validateFirstName(fname)
{
var f = document.forms["NewUser"]["fName"].value;
var fLength = f.length;
var illegalChars = /\W/;
if(fLength > 20)
{
return "First Name has a max of 20 characters";
}
else if (illegalChars.test(f))
{
return "Numbers,letter and underscores in first name only";
}
else
{
return "";
}
}
function validateLastName(lName)
{
var l = document.forms["NewUser"]["lName"].value;
var lLength = l.length;
var illegalChars = /\W/;
if(lLength > 100)
{
return "Last Name has a max of 100 characters";
}
else if (illegalChars.test(f))
{
$("#ErrorLname").text("Numbers,letter and underscores in last name only";
}
else
{
return "";
}
}
function validateForm()
{
/*
valid = true;
//call username function
valid = valid && validateUserName();
//call password function
valid = valid && validatePassword();
//call email function
valid = valid && validateEmail();
//call first name function
valid = valid && validateFirstName();
//call first name function
valid = valid && validateLastName();
return valid;
*/
var error = "";
//call username function
error += "\n"+validateUserName();
//call password function
error += "\n"+validatePassword();
error += "\n"+validateEmail();
error += "\n" + validateFirstName();
error += "\n" + validateLastName();
if(error === ""){
return true;
}
else{
$("#ErrorUser").text(error);
$("#ErrorEmail").text(error);
$("#ErrorFname").text(error);
$("#ErrorPassword1").text(error);
$("#ErrorLname").text(error);
return false;
}
}
$('#your-form').submit(validateForm);
Fiddle: http://jsfiddle.net/cyKgD/
You had few errors in your code.
The validateForm() is never being called
Line 174: Should be else if (illegalChars.test(l))
Line 113: Closing bracket missing
This fiddle seems to be working now, http://jsfiddle.net/u5565/
Make sure that jQuery is included in your page. The line of code
$(function() {
$('#your-form').submit(function() {
return validateForm();
});
});
tells jQuery to validate the form when it is submitted.
In your fiddle, you forgot method="POST" on the form tag
<form name = "NewUser" id = "your-form" method="POST">

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.

js forms clearing after validate

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.

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