Jump to content

Form Verification Using Javascript


emmaclarke
 Share

Recommended Posts

I'm trying to do some form verification using a postcode. If the postcode begins with either MK1-MK15, MK17, MK19, MK77 they should receive a message saying they will get a special gift.

(function() { // Do everything in this one anonymous function	// When the document finishes loading, call init()	if (window.addEventListener) window.addEventListener("load", init, false);	else if (window.attachEvent) window.attachEvent("onload", init);	// Define event handlers for any forms and form elements that need them.	function init() {		// Loop through all forms in the document		for(var i = 0; i < document.forms.length; i++) {			var f = document.forms[i];  // the form we're working on now			// Assume, for now, that this form does not need any validation			var needsValidation = false;			// Now loop through the elements in our form			for(j = 0; j < f.elements.length; j++) {				var e = f.elements[j];  // the element we're working on				// We're only interested in <input type="text"> textfields				if (e.type != "text") continue;				// See if it has attributes that require validation				var pattern = e.getAttribute("pattern");				// We could use e.hasAttribute() but IE doesn't support it				var required = e.getAttribute("required") != null;				// Required is just a shortcut for a simple pattern				if (required && !pattern) {					pattern = "\\S";					e.setAttribute("pattern", pattern);				}				// If this element requires validation,				if (pattern) {					// validate the element each time it changes					e.onchange = validateOnChange;					// Remember to add an onsubmit handler to this form					needsValidation = true;				}			}			// If at least one of the form elements needed validation,			// we also need an onsubmit event handler for the form			if (needsValidation) f.onsubmit = validateOnSubmit;		}	}		  	// This function is the onchange event handler for textfields that 	// require validation.  Remember that we converted the required attribute	// to a pattern attribute in init().	function validateOnChange() {		var textfield = this;							// the textfield		var pattern = textfield.getAttribute("pattern"); // the pattern		var value = this.value;						  // the user's input		// If the value does not match the pattern set the class to "invalid".		if (value.search(pattern) == -1) textfield.className = "invalid";		else textfield.className = "valid";	}	// This function is the onsubmit event handler for any form that 	// requires validation.	function validateOnSubmit() {		// When the form is submitted, we revalidate all the fields in the		// form and then check their classNames to see if they are invalid.		// If any of those fields are invalid, display an alert and prevent		// form submission.		var invalid = false;  // Start by assuming everything is valid		// Loop through all form elements		for(var i = 0; i < this.elements.length; i++) {			var e = this.elements[i];			// If the element is a text field and has our onchange handler			if (e.type == "text" && e.onchange == validateOnChange) {				e.onchange(); // Invoke the handler to re-validate				// If validation fails for the element, it fails for the form				if (e.className == "invalid") invalid = true;			}						if(  pattern == "MK1" ||  pattern == "MK2" ||  pattern == "MK3" ||  pattern == "MK4" ||  pattern == "MK5" ||  pattern == "MK6" ||  pattern == "MK7" ||  pattern == "MK8" ||  pattern == "MK9" ||  pattern == "MK10" ||  pattern == "MK11" ||  pattern == "MK12" ||  pattern == "MK13" ||  pattern == "MK14" ||  pattern == "MK15" ||  pattern == "MK17" ||  pattern == "MK19" ||  pattern == "MK77")			{			alert("You will receive a special gift");			}		}		// If the form is invalid, alert user and block submission		if (invalid) {			alert("The form is incompletely or incorrectly filled out.\n" +				  "Please correct the  highlighted fields and try again.");			return false;		}	}})();

I've put the code in submit form function and assume the verification takes place here. It doesn't work however and no alert is shown. I'm not sure whether to put a javascript function actually on the HTML web page where the form code is:

<td>Postal Code</td>		  <td><input type="text" name="shipPostalCode" maxlength=		  "30" pattern="\w{2,}\d{1,2}\s*\d{1,2}\w{2,}" /></td>		</tri.e. put a javascript function here if pattern == MK17 etc

Link to comment
Share on other sites

function validateOnSubmit() {		// When the form is submitted, we revalidate all the fields in the		// form and then check their classNames to see if they are invalid.		// If any of those fields are invalid, display an alert and prevent		// form submission.		var invalid = false;  // Start by assuming everything is valid		// Loop through all form elements		for(var i = 0; i < this.elements.length; i++) {			var e = this.elements[i];			// If the element is a text field and has our onchange handler			if (e.type == "text" && e.onchange == validateOnChange) {				e.onchange(); // Invoke the handler to re-validate				// If validation fails for the element, it fails for the form				if (e.className == "invalid") invalid = true;																// We're only interested in <input type="text"> textfields				if (e.type != "text") continue;				// See if it has attributes that require validation				var pattern = e.getAttribute("pattern");				// We could use e.hasAttribute() but IE doesn't support it				var required = e.getAttribute("required") != null;						//If the postcode begins with MK1-MK15, MK17, MK19, MK77 get a special message		if(pattern == "MK17") {		alert("You will receive a special gift");		}						}																							}

I looked and saw where the if statement was it couldn't reach or didn't know the value of pattern so I put it in the loop where it iterates over all the elements of the form and gets the value of pattern I still don't think its getting the pattern value though for some reason. // See if it has attributes that require validation var pattern = e.getAttribute("pattern");I'm sure this gets the pattern value.

Link to comment
Share on other sites

function validateOnSubmit() {		// When the form is submitted, we revalidate all the fields in the		// form and then check their classNames to see if they are invalid.		// If any of those fields are invalid, display an alert and prevent		// form submission.		var invalid = false;  // Start by assuming everything is valid		// Loop through all form elements		for(var i = 0; i < this.elements.length; i++) {			var e = this.elements[i];						 // See if it has attributes that require validation				var text = e.getAttribute("text");								alert(text);															//If the postcode begins with MK1-MK15, MK17, MK19, MK77 get a special message		if(text == "MK17") {		alert("You will receive a special gift");		}												// If the element is a text field and has our onchange handler			if (e.type == "text" && e.onchange == validateOnChange) {				e.onchange(); // Invoke the handler to re-validate				// If validation fails for the element, it fails for the form				if (e.className == "invalid") invalid = true;																						}

i've tried to get the data from the text fields by using e.getAttribute("text") and then do an alert for what is in text and null just keeps coming up.

Link to comment
Share on other sites

for(var i = 0; i < this.elements.length; i++) {			var e = this.elements[i];						 			 			 			 			 if (i == 5) {			 			 			 			 // See if it has attributes that require validation				var postcode = e.getAttribute("postcode");								alert(postcode);								var text = e.value;								alert("text is " + text);												if (text == "MK17") {				alert("you will receive a special gift");				}																			}

OK this works kind of.If you enter MK17 as your postal code it will come up with "you will receive a special gift"If you enter MK17 17AB for example the message "you will receive a special gift" will not come up.How can you just let it read the first part of the postal code and ignore the rest of it? I.E. The first 3 or 4 digits to the postal code text string? Bear in mind it is a string and not an array.Your help appreciated.

Link to comment
Share on other sites

You can either use String.substring to get part of a string, or you can use String.split to split up the value into an array, so you could split on the space and get everything before the first space in the first element of the array.https://developer.mozilla.org/en/Core_JavaS...tring/substringhttps://developer.mozilla.org/en/Core_JavaS...ts/String/split

Link to comment
Share on other sites

 function validateOnSubmit() {		// When the form is submitted, we revalidate all the fields in the		// form and then check their classNames to see if they are invalid.		// If any of those fields are invalid, display an alert and prevent		// form submission.		var invalid = false;  // Start by assuming everything is valid		// Loop through all form elements		for(var i = 0; i < this.elements.length; i++) {			var e = this.elements[i];						 // If the element is a text field and has our onchange handler			if (e.type == "text" && e.onchange == validateOnChange) {				e.onchange(); // Invoke the handler to re-validate				// If validation fails for the element, it fails for the form				if (e.className == "invalid") invalid = true;																						}			 			 			 // using the 5th form element which is the post code element			 if (i == 5) {			 			 			 // using this elements value and putting it in variable text i.e. the postcode's value												var text = e.value;								//conditions on beginning of the postcode to receive a special gift message, verifying each array element in the string for the position of the postcode								if (text[0] == "M" || "m" && text[1] == "K" || "k" && text[2] == "1" || "7" && text[3] == "7" || "1" || "2" || "3" || "4" || "5") {				alert("you will receive a special gift");				}										}														 // If the form is invalid, alert user and block submission		if (invalid) {			alert("The form is incompletely or incorrectly filled out.\n" +				  "Please correct the  highlighted fields and try again.");			return false;		}																							}																								 					}})();

OK it all works - the postcode beginning check, validation check pattern on postcode and pattern check on the fidielity card using a pattern.

Link to comment
Share on other sites

It's probably better to split the string up into an array instead of trying to access the characters using array syntax. You can use split without a character to create an array of characters from the string.var ar = text.split("");Also, this won't work:if (text[0] == "M" || "m")you need to do this:if (text[0] == "M" || text[0] == "m")You can also convert the string to uppercase or lowercase first.

Edited by justsomeguy
Link to comment
Share on other sites

// using the 5th form element which is the post code element			 if (i == 5) {			 			 			 // using this elements value and putting it in variable text i.e. the postcode's value												var text = e.value;								var text = text.split("");								alert(text[0]);								//conditions on beginning of the postcode to receive a special gift message, verifying each array element in the string for the position of the postcode								if (text[0] == "M") { // && text[1] == "K" || "k" && text[2] == "1" || "7" && text[3] == "7" || "1" || "2" || "3" || "4" || "5") {				alert("you will receive a special gift");				}										}

this now works.

Link to comment
Share on other sites

//conditions on beginning of the postcode to receive a special gift message, verifying each array element in the string for the position of the postcode								if (text[0] == "M" || text[0] == "m" && text[1] == "K" || text[1] "k" && text[2] == "1" || text[2] == "7" && text[3] == "7" || text[3] == || "1" || text[3] == "2" || text[3] == "3" || text[3]== "4" || text[3] == "5") {				alert("you will receive a special gift");				}										}

for some reason if i just use if text[0] == "M" it works, but if i use all the conditions above it doesn't work.

Link to comment
Share on other sites

 // using the 5th form element which is the post code element			 if (i == 5) {			 			 //accessing and iterating over the first four characters in postcode			 for(i = 0; i < 4; i++){			 			 text[i];			 alert(text[i]);			 			 // using this elements value and putting it in variable text i.e. the postcode's value												var text = e.value;				//split the string up into an array				var text = text.split("");								alert(text[3]);								//conditions on beginning of the postcode to receive a special gift message, verifying each array element in the string for the position of the postcode								if (text[0] == "M" || text[0] == "m" && text[1] == "K" || text[1] "k") { // && text[2] == "1" || text[2] == "7" && text[3] == "7" || text[3] == || "1" || text[3] == "2" || text[3] == "3" || text[3]== "4" || text[3] == "5") {				alert("you will receive a special gift");				}			}							}

For some reason I don't think the

if(i = 0; i<4; i++){ text[i]; alert(text[i]);}

is working because it shows no alert message.

Link to comment
Share on other sites

 // using the 5th form element which is the post code element			 if (i == 5) {			 			 //accessing and iterating over the first four characters in postcode			 for(a = 0; a < 4; a++){			 			 // using this elements value and putting it in variable text i.e. the postcode's value			 var text = e.value;			 				//split the string up into an array				var text = text.split("");			 			 text[a];			 			 alert(text[3]);																									//conditions on beginning of the postcode to receive a special gift message, verifying each array element in the string for the position of the postcode								if (text[0] == "M" || text[0] == "m" && text[1] == "K" || text[1] == "k" && text[2] == "1" || text[2] == "7" && text[3] == "7" || text[3] == || "1" || text[3] == "2" || text[3] == "3" || text[3]== "4" || text[3] == "5") {				alert("you will receive a special gift");				}			}							}

There must be something wrong with the :

if (text[0] == "M" || text[0] == "m" && text[1] == "K" || text[1] == "k" && text[2] == "1" || text[2] == "7" && text[3] == "7" || text[3] == || "1" || text[3] == "2" || text[3] == "3" || text[3]== "4" || text[3] == "5")

statement because it won't even show alert(text[0]) like it was before.If I do this as an if statement :=[/code]//conditions on beginning of the postcode to receive a special gift message, verifying each array element in the string for the position of the postcode if (text[0] == "M" || text[0] == "m"){ alert("you will receive a special gift"); } } }[/code]it will show the alert(text[3]) correct character so i'm not sure if there is something wrong in that IF statement or if it is too long or wrong conditions???

Link to comment
Share on other sites

You need to take order of operations into consideration. OR and AND get evaluated in a different order. Add parentheses to your condition to clarify what you want it to check.

if ((text[0] == "M" || text[0] == "m") && (text[1] == "K" || text[1] == "k") && ...

Link to comment
Share on other sites

//conditions on beginning of the postcode to receive a special gift message, verifying each array element in the string for the position of the postcode								if ((text[0] == "M" || text[0] == "m") && (text[1] == "K" || text[1] == "k") && (text[2] == "1" || text[2] == "7") && (text[3] == "7" || text[3] == || "1" || text[3] == "2" || text[3] == "3" || text[3]== "4" || text[3] == "5")) {				alert("you will receive a special gift");				}			}

still doesn't work

Link to comment
Share on other sites

That should work for the conditions you're checking. I mean, that's a valid if statement. Are you checking for the right things for your application? That's going to evaluate to true if the first character is "m", the second is "k", the third is a 1 or 7, and the fourth is 1-5 or 7.

Link to comment
Share on other sites

//conditions on beginning of the postcode to receive a special gift message, verifying each array element in the string for the position of the postcode

				if ((((text[0] == "M" || text[0] == "m") && (text[1] == "K" || text[1] == "k") && (text[2] == "1" || text[2] == "7") && (text[3] == "7" || text[3] == "1" || text[3] == "2" || text[3] == "3" || text[3]== "4" || text[3] == "5")))) {				alert("you will receive a special gift");				}

the parentheses are now correct and is working.

Link to comment
Share on other sites

if ((((text[0] == "M" || text[0] == "m") && (text[1] == "K" || text[1] == "k") && (text[2] == "1" || text[2] == "2" || text[2] == "3" || text[2] == "4" || text[2] == "5" || text[2] == "6" || text[2] == "7" || text[2] == "8" || text[2] == "9")))) {								alert("you will receive a special gift");								}								if ((((text[0] == "M" || text[0] == "m") && (text[1] == "K" || text[1] == "k") && (text[2] == "1" && text[3] == "0" || text[2] == "1" && text[3] == "1" || text[2]== "1" && text[3] == "2" || text[2] == "1" && text[3] == "3" || text[2] == "1" && text[3] == "4" || text[2] == "1" && text[3] == "5" || text[2] == "1" && text[3] == "7" || text[2] == "1" && text[3] == "9")))){  								alert("you will receive a special gift");				}

For some reason if i enter MK16 16AB i get the alert message when there is no condition for text[2] == 1 && text[3] == 6

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...