VirtualMV/JavaScript/Validation
Overview
By the end of this page you will be able to:
|
Basic validation (js5_01)
js5_01.htm
<html> <head> <title>E-Mail Submit (js5_01)</title> <script type="text/javascript" src="js5_01.js"></script> </head> <body> <form name="frmDetails"> <table> <tr><td>Name:</td> <td><input name="txtName" type="text" value="" /></td></tr> <tr><td>E-mail:</td> <td><input name="txtEmail" type="text" value="" /></td></tr> <tr><td>Post Code:<br>(exactly 5 digits please)</td> <td><input name="txtPostCode" type="text" value="" /></td></tr> </table> <p><input type="button" name="Submit" value="Submit" onClick="fnCheckOK()" /></p> <textarea name="message" rows="7" cols="40" ></textarea> </form> </body> </html>
js5_01.js
function fnNameOK() { strName=document.frmDetails.txtName.value if((strName=="")||!isNaN(strName)) {return false} else {return true} } function fnEmailOK() { strEmail=document.frmDetails.txtEmail.value if((strEmail=="")|| !isNaN(strEmail)) { /* alert("email"); */ return false;} else {return true} } function fnPostCodeOK() { strPostCode=document.frmDetails.txtPostCode.value if((strPostCode=="")|| isNaN(strPostCode) || (strPostCode.length)!=5) {return false} else {return true} } function fnCheckOK() { if(fnNameOK() && fnEmailOK() && fnPostCodeOK()) { document.frmDetails.message.value="The following information has been submitted:" +"\r\r"+strName+"\r"+strEmail+"\r"+strPostCode; } else {alert("You have entered bad information into one or more fields"); } }
Note: there is an example of some debugging code in fnEmailOK (between /* and */). If you remove the comment tags, and there is an error in the email an alert box will appear. (Obviously this code is commented out or removed in the production/live version).
Example :Click here to run js5_01.
eMail validation
js5_01a.js
function fnNumchar(strText,strChar){ intPos = 0 for (i=0; i<(strText.length); i++) { if(strText.charAt(i)==strChar) {intPos=i+1 } } return intPos; } function fnEmailOK() { strEmail=document.frmDetails.txtEmail.value if((strEmail=="")|| !isNaN(strEmail) || ((strEmail.length)<5) || (fnNumchar(strEmail," ")>0) || (fnNumchar(strEmail,"@")<=1) || (fnNumchar(strEmail,".")==0)) {return false} else {return true} }
If any of the following occur the email returns false ( || = or )
- strEmail=="" nothing is entered
- !isNaN(strEmail) Not (NOT a (!) Null) - actually says is it null
- Email.length)<5 : length <= 4 char
- fnNumchar(strEmail," ")>0 : If there is a space in the string
- fnNumchar(strEmail,"@")<=1) : If @ is not in the string (0) or in the first position
- fnNumchar(strEmail,".")==0 : If a . is not in the string
Note you could rewrite the function using the IndexOf() function
Validation using a common function (js5_FormVal_TxtNotEmpty.html)
A little more sophisticated, this code uses a form containing first and last name, checks to see if any data has been entered. If either field is blank it will change the background colour and produce a message on the form using getElementById.
<html> <head> <title>Form validation text not empty</title> <script type="text/javascript"> function fnNameOK(strName) { if((strName.value=="")||!isNaN(strName.value)) { strName.style.background = "#FBEC5D"; return false} else {return true} } function fnCheckOK() { strMsg = "" objForm = document.frmDetails; //makes it easier to specify objects on the form objForm.txtFName.style.background = "#FFFFFF"; if(!fnNameOK(objForm.txtFName)) { strMsg +=": first name "; } objForm.txtLName.style.background = "#FFFFFF"; if(!fnNameOK(objForm.txtLName)) { strMsg +=": last name "; } if(strMsg.length == 0) { document.getElementById('Msg').innerHTML = "No errors"; } else { document.getElementById('Msg').innerHTML = "Errors in " + strMsg; } } </script> </head> <body> <form name="frmDetails"> <p>Check that data has been entered into both fields</p> <p>FirstName:<input name="txtFName" type="text" value="" /> LastName: <input name="txtLName" type="text" value="" /></p> <p><input type="button" name="Submit" value="Submit" onClick="fnCheckOK()" /></p> <div id="Msg"></div> </form> </body> </html>
Example :Click here to run js5_FormVal_TxtNotEmpty.html. Example :Click here to run js5_FormVal_TxtNotEmpty.
Exercise: We can improve the code slightly by adding the background to white ("#FFFFFF") statement into the function fnNameOK(strName) |
---|
Add the background change before the if statement and remove the change from fnCheckOK()
function fnNameOK(strName) { strName.style.background = "#FFFFFF"; if((strName.value=="")||!isNaN(strName.value)) { strName.style.background = "#FBEC5D"; return false} else {return true} } |
Date validation
Dates can be validated by parsing the date string (or using regular expressions). An example of date validation using string methods can be found at SmartWebby (2009)[1]
Example :Click here to run jsValDate_01.
To compare dates it is easiest to compare the international date format yyyymmdd e.g. 20100602 is greater than 20100131. (in the New Zealand date format ddmmyyyy this is not true as 31012010 > 02062010). To simplify user input I suggest you put the format you want onto the form. If you want to use the country specific format (e.g. NZ dd/mm/yyyy) use string manipulation to change to yyyymmdd then compare.
A very clever way to test if a date is valid, is to ask JavaScript to create a date from your values then test them
var intYear = "2011"; var intMonth = "12"; var intDay = "1"; var objDate = new Date(intYear, intMonth-1, intDay); if ((objDate.getMonth()+1!=intMonth)||(objDate.getDate()!=intDay)||(objDate.getFullYear()!=intYear)) { //display error }
Comparing two dates can be achieved using the date object:
var x=new Date(); x.setFullYear(2012,0,14); var today = new Date(); if (x>today) { alert("Today is before 14th January 2012"); } else { alert("Today is after 14th January 2012"); }
Some test data
The following list shows some dates you can use to test your date routine. (I am using a dd/mm/yyyy format)
- 01/01/2010, 31/12/2010 - valid (always check it works before testing for errors :) )
- dd (day invalid) 99/01/2010, a1/01/2010, 30/02/2010 (Feb max 29), 31/09/2010 (Sep max 30)
- mm (month invalid) 01/99/2010, 01/aa/2010
- yyyy (year invalid) 01/01/10
Depending on your implementation you may also need to check 1/4/10 (shortened input)
Phone number validation
- You will find many examples of JavaScript where phone numbers are validated using a mask (e.g. (##) ###-#### ). Personally, I think mask based phone numbers create more problems than they solve. E.g. 111 (or 911) are valid phone numbers, 4 digit mobile numbers exist, as do a wide variety of freephone (0800) 123-123 and cell phone numbers.
- For phone numbers I think it is adequate to check for numerics, space, brackets () and a dash. You may want to consider alphabetic numbers e.g. 0800 CALL ME depending on your application.
Adding a form (using connected media)
It is also possible to add a form using public server based systems such as Google docs and email me form. This has the advantage of getting around the local email client requirement, however, as customer data is routed via someone else's server think about the security of the data.
Refer to Adding a form for more details.
References
- ↑ SmartWebby (2009) DHTML date validation script for dd/mm/yyyy. Retrieved June 10, 2009 from http://www.smartwebby.com/dhtml/
- ↑ Refsnes Data (2012) w3Schools. Retrieved from http://www.w3schools.com/js/js_obj_date.asp
virtualMV | Superquick wiki guide | Please give me some feedback |
VirtualMV/JavaScript/Validation. (2024). In WikiEducator/VirtualMV wiki. Retrieved November 21, 2024, from http:https://wikieducator.org/VirtualMV/JavaScript/Validation (zotero)
|