sheffrem Posted February 19, 2009 Share Posted February 19, 2009 Hi all, im new to javascript, i have been playing with validation but its giving trouble. It give the required message to do when the field is empty or the the data entered is invalid. here is the code. <html> <head> <script> function validate(){ //------------------------------- var f_name=document.form.fname.value; // validate fname + Specifying the characters that can go in the field. var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; for (i=0; i< f_name.length; i++) { var c=f_name.charAt(i); if (valid.indexOf©==-1) { alert ("The Full name field cannot Contain this Character"); document.form.fname=""; document.form.fname.focus=""; return false; } } if(f_name=="") { alert("Please fill the form"); document.form.fname.focus(); return false; } // validate telephone ------------------------------- var t=document.form.tel.value; if(t=="") { alert ("Please fill the form"); document.form.tel.focus(); return false; } if(t.length <10 || t.length>12){ alert("PLs fill the phone number field correctly"); document.write.form.tel.value=""; document.write.form.tel.value.focus=""; return false; } else{ return true; } } </script> <title> FORM VALIDATION </title> </head> <body bgcolor=lavender background=bg.jpg> <br> <br> <table align=center border=1 width=300 bgcolor=white cellpadding=6> <tr> <form method="post" action="action.html" name="form" onsubmit="return validate()"> <tr> <td>Full Name: </td> <td><input type=text name=fname> <br> </td> </tr> <tr> <td>Telephone: </td> <td> <input type=text name=tel> <br> </td> </tr> <tr> <td> </td> <td> <input type=submit value=submit> <br> </td> </tr> </form> </center> </body> </html> Quote Link to comment Share on other sites More sharing options...
darkfreaks Posted February 27, 2009 Share Posted February 27, 2009 Fixed Code: function validate(){ //------------------------------- var f_name=document.form.fname.value; // validate fname + Specifying the characters that can go in the field. var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVW XYZ"; for (i=0; i< f_name.length; i++) { var c=f_name.charAt(i); if (valid.indexOf(c)==-1) { alert ("The Full name field cannot Contain this Character"); document.form.fname=""; document.form.fname.focus=""; return false; } } if(f_name==="") { alert("Please fill the form"); document.form.fname.focus(); return false; } // validate telephone ------------------------------- var t=document.form.tel.value; if(t==="") { alert ("Please fill the form"); document.form.tel.focus(); return false; } if(t.length <10 || t.length>12){ alert("PLs fill the phone number field correctly"); document.form.tel.value=""; document.form.tel.value.focus=""; return false; } else{ return true; } } Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.