Professional Documents
Culture Documents
com/development/
var toggle var body = document.getElementById("body") if (confirm("Do you wish to change the background colour of this page?")) { if (toggle) { body.style.backgroundColor = '#ffcc00' toggle = false } else { body.style.backgroundColor = '#d30300' toggle = true } }
Nan Function:-
var x = prompt("Enter a value to test if it is numerical.") if (isNaN(x)) { alert('"' + x + '" is not a number.') } else { alert('"' + x + '" is a number.') }
Void function:
< html> < head> < script type= "text/javascript"> < !-//--> < /script> < /head> < body> < p> Click the following, This won't react at all...< /p> < a href= "javascript:void(0))"> Click me!< /a> < /body> < /html>
R eg ular ex pression:
A regular expression could be defined with the RegExp( ) constructor like this:
html> <head> <script type="text/javascript" src="validate.js"></script> </head> <body> <form action="#" name="StudentRegistration" onsubmit="return(validate());">
</tr> <tr> <td>Postal Address</td> <td><input type="text" name="paddress" id="paddress" size="30"></td> </tr>
<tr> <td>Sex</td> <td><input type="radio" name="sex" value="male" size="10">Male <input type="radio" name="sex" value="Female" size="10">Female</td> </tr>
<tr> <td>City</td> <td><select name="City"> <option value="-1" selected>select..</option> <option value="New Delhi">NEW DELHI</option> <option value="Mumbai">MUMBAI</option> <option value="Goa">GOA</option> <option value="Patna">PATNA</option>
</select></td> </tr>
<tr> <td>Course</td> <td><select name="Course"> <option value="-1" selected>select..</option> <option value="B.Tech">B.TECH</option> <option value="MCA">MCA</option> <option value="MBA">MBA</option> <option value="BCA">BCA</option> </select></td> </tr>
<tr> <td>District</td> <td><select name="District"> <option value="-1" selected>select..</option> <option value="Nalanda">NALANDA</option> <option value="UP">UP</option> <option value="Goa">GOA</option> <option value="Patna">PATNA</option> </select></td>
</tr>
<tr> <td>State</td> <td><select Name="State"> <option value="-1" selected>select..</option> <option value="New Delhi">NEW DELHI</option> <option value="Mumbai">MUMBAI</option> <option value="Goa">GOA</option> <option value="Bihar">BIHAR</option> </select></td> </tr> <tr> <td>PinCode</td> <td><input type="text" name="pincode" id="pincode" size="30"></td>
<tr>
<td>MobileNo</td> <td><input type="text" name="mobileno" id="mobileno" size="30"></td> </tr> <tr> <td><input type="reset"></td> <td colspan="2"><input type="submit" value="Submit Form" /></td> </tr> </table> </form> </body> </html> Form Validation
function validate() { if( document.StudentRegistration.textnames.value == "" ) { alert( "Please provide your Name!" ); document.StudentRegistration.textnames.focus() ; return false; } if( document.StudentRegistration.fathername.value == "" ) { alert( "Please provide your Father Name!" ); document.StudentRegistration.fathername.focus() ; return false;
if( document.StudentRegistration.paddress.value == "" ) { alert( "Please provide your Postal Address!" ); document.StudentRegistration.paddress.focus() ; return false; } if( document.StudentRegistration.personaladdress.value == "" ) { alert( "Please provide your Personal Address!" ); document.StudentRegistration.personaladdress.focus() ; return false; } if ( ( StudentRegistration.sex[0].checked == false ) && ( StudentRegistration.sex[1].checked == false ) ) { alert ( "Please choose your Gender: Male or Female" ); return false; } if( document.StudentRegistration.City.value == "-1" ) { alert( "Please provide your City!" ); document.StudentRegistration.City.focus() ; return false; } if( document.StudentRegistration.Course.value == "-1" )
return false; } if( document.StudentRegistration.District.value == "-1" ) { alert( "Please provide your Select District!" );
return false; } if( document.StudentRegistration.State.value == "-1" ) { alert( "Please provide your Select State!" );
return false; } if( document.StudentRegistration.pincode.value == "" || isNaN( document.StudentRegistration.pincode.value) || document.StudentRegistration.pincode.value.length != 6 ) { alert( "Please provide a pincode in the format ######." ); document.StudentRegistration.pincode.focus() ; return false; } var email = document.StudentRegistration.emailid.value;
atpos = email.indexOf("@"); dotpos = email.lastIndexOf("."); if (email == "" || atpos < 1 || ( dotpos - atpos < 2 )) { alert("Please enter correct email ID") document.StudentRegistration.emailid.focus() ; return false; } if( document.StudentRegistration.dob.value == "" ) { alert( "Please provide your DOB!" ); document.StudentRegistration.dob.focus() ; return false; } if( document.StudentRegistration.mobileno.value == "" || isNaN( document.StudentRegistration.mobileno.value) || document.StudentRegistration.mobileno.value.length != 10 ) { alert( "Please provide a Mobile No in the format 123." ); document.StudentRegistration.mobileno.focus() ; return false; } return( true ); }
validation:
Client-Side Validation
While client-side validation is often much faster and provides the user with a very good experience, it is important to note that client-side validation should NOT replace server-side validation. This is mainly because of security among other reasons and also because JavaScript can be turned off on some web browsers. This article will look at the following areas of form development: Form Design Form Validation Error Message Display
</tr> </table> </fieldset> <fieldset> <legend>Other Information</legend> <table border="0"> <tr> <td width="59"><label for="name">Name</label></td> <td width="207"><input type="text" id="name" class="required text"/>*</td> </tr> <tr> <td><label for="phone">Phone</label></td> <td><input type="text" id="phone" class="phone text"/></td> </tr> <tr> <td> </td> <td><input type="submit" value="Submit Form" class="submit"/></td> </tr> <tr> <td colspan="2">* = Required Field</td> </tr> </table> </fieldset> </form> </body> </html>
/* CSS Document */ form { font-family: Arial; font-size: 14px; width: 300px; } fieldset {
border: 1px solid #CCC; margin-bottom: 10px; } fieldset.login input { width: 125px; } legend { font-weight: bold; font-size: 1.1em; } label { display: block; width: 60px; text-align: right; float: left; padding-right: 10px; margin: 5px 0; } input { margin: 5px 0; } input.text { padding: 0 0 0 3px; width: 172px; } input.submit { margin: 15px 0 0 70px; } .tooltip{ font-style:italic; color:#666666; font-size:9px; } .errormsg{
color:#FF0000; font-size:9px; font-weight:bold; } #errmsgbox{ border:dotted #FFCC66 1px; background-color:#FFFFCC; width:300px; height:60px; color:#FF0000; font-size:15px; font-weight:bold; } Here's what the form looks like on a web page:
To check for blanks, we create a function that will go through all the fields on the form to see if they contain any values, and show an appropriate error message: function checkblanks(pform1){ if(pform1.username.value==""){ alert("Please enter a user name") pform1.username.focus() return false } if(pform1.password.value==""){ alert("Please enter a password") pform1.password.focus() return false } if(pform1.name.value==""){ alert("Please enter a name") pform1.name.focus() return false } if(pform1.email.value==""){ alert("Please enter a email") pform1.email.focus() return false } return true } The code above checks for blanks by accessing the form elements by name. Because of the design of our form we could also access these elements by their IDs. More specifically, the code checks the values property of the form elements if they contain any values. A alert dialog box pops up to notify the user of any blank fields. The next code will validate the type of data that is entered and also checks that the correct number of charcters is included. JavaScript can handle a variety of data types including integers and strings. The main reason for checking data types is so that server side validation runs smoothly. In many instances, data captured in forms are posted to a database. This means that strings, integers and dates have to be in the correct format in order for it to be correctly stored in a database. Our password should be minimum four characters and maximum eight characters: function checkpassword(pform1){ var str=pform1.password.value;
//check required fields //password should be minimum 4 chars but not greater than 8 if ((str.length < 4) || (str.length > 8)) { alert("Invalid password length.") pform1.password.focus() return false } } The function above first captures the submitted password and stores it in a variable called "str": var str=pform1.password.value; then it counts the number of characters (using the length() function) in the password to see if it meets the set restriction relating to its character count: if ((str.length < 4) || (str.length > 8)) If it does not pass the test then an alert message is shown to notify the user thereof: alert("Invalid password length.") To ensure that the password is not a number we use the isNAN() function like so: if(!isNaN(str)){ alert="this is not a number"; pform1.password.focus() return false }
var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/; if(!(validemail.test(email))){ alert("Invalid email address") pform1.email.focus() return false } //check phone number if (isNaN(parseInt(cleanstr))) { alert("The phone number contains unwanted characters.") } } So what did we do here? First of all, we captured the two values for email and phone number that was sent from the form: var email = pform1.email.value; var phone = pform1.phone.value; Then we declare a validemail pattern for the email address: var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/; To understand the regular expression we will divide it into smaller parts, so that it makes sense: /^[a-zA-Z0-9._-]+: Means that the email address must begin with alpha-numeric characters (both lowercase and uppercase characters are allowed). It may have periods, underscores and hyphens. @: There must be a '@' symbol after initial characters. [a-zA-Z0-9.-]+: After the '@' sign there must be some alpha-numeric characters. It can also contain period ('.') and and hyphens('-'). .: After the second group of characters there must be a period ('.'). This is to separate domain and subdomain names. [a-zA-Z]{2,4}$/: Finally, the email address must end with two to four alphabets. Having a-z and A-Z means that both lowercase and uppercase letters are allowed. {2,4} indicates the minimum and maximum number of characters. This will allow domain names with 2, 3 and 4 characters e.g.; na,us, tx, org, com, net, wxyz). Now that you have some basic understanding of regular expressions, let's continue with the code: We now need to compare the submitted email address against the "validemail" pattern that we defined earlier: if(validemail.test(email)){ The "test()" property tries to match the submitted email against the pattern that we submitted. We simply notify the user if the test fails: }else{
err.message="Invalid email"; err.field=pform1.email; } To validate a phone number, we must first clear out any unwanted characters. To achieve this We use regular expression and the replace () function. It will replace anything that we have placed in our pattern of unwanted characters with a empty string: var cleanstr = phone.replace(/[().- ]/g, ''); Then we look at what we have left with the isNaN() function. This function checks if a given value is a number or not: if (isNaN(parseInt(cleanstr))) { alert("Invalid phone number.") }
//check phone number if (isNaN(parseInt(cleanstr))) { err.message="Invalid phone number"; err.field=pform1.phone; } if(err.message) { document.getElementById('divError').innerHTML = err.message; err.field.focus(); return false; } return true } The code above takes all the error messages step by step and then displays them in the divError tag that is displayed at the top of the form.
HTML, CSS and JavaScript for the Whole Web Page and Form
Below is the entire form: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Form Handling</title> <link href="formstyle.css" rel="stylesheet" type="text/css" /> <script language="javascript" type="text/javascript"> function checkform(pform1){ var str=pform1.password.value; var email = pform1.email.value; var phone = pform1.phone.value; var cleanstr = phone.replace(/[\(\)\.\-\ ]/g, ''); var err={}; var validemail =/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; //check required fields //password should be minimum 4 chars but not greater than 8 if ((str.length < 4) || (str.length > 8)) { err.message="Invalid password length"; err.field=pform1.password;
} //validate email if(!(validemail.test(email))){ err.message="Invalid email"; err.field=pform1.email; } //check phone number if (isNaN(parseInt(cleanstr))) { err.message="Invalid phone number"; err.field=pform1.phone; } if(err.message) { document.getElementById('divError').innerHTML = err.message; err.field.focus(); return false; } return true } </script> </head> <body> <h1>Improved Form Handling with JavaScript</h1> <form action="" method="POST" onsubmit="return checkform(this);"> <div id="errmsgbox"> <div id="divError"></div> </div> <fieldset class="credentials"> <legend>Access Credentials</legend> <table border="0"> <tr>
<td><label for="username" class="hover">Username</label></td> <td><input type="text" id="username" class="required text"/> <span class="style1">*</span></td> </tr> <tr> <td><label for="password" class="hover">Password</label></td> <td><input type="password" id="password" class="required text"/> <span class="style1">*</span><br /> <span class="tooltip">Minimum four and maximum eight characters</span> </td> </tr> <tr> <td><label for="email">Email</label></td> <td><input type="text" id="email" class="required email text"/> <span class="style1">*</span></td> </tr> </table> </fieldset> <fieldset> <legend>Other Information</legend> <table border="0"> <tr> <td width="59"><label for="name">Name</label></td> <td width="207"><input type="text" id="name" class="required text"/> <span class="style1">*</span></td> </tr> <tr> <td><label for="phone">Phone</label></td> <td><input type="text" id="phone" class="phone text"/></td> </tr> <tr> <td colspan="2"><input type="submit" value="Submit Form" class="submit"/></td> </tr> <tr> <td colspan="2">* = Required Field</td> </tr> </table> </fieldset> </form> </body> </html>