By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,865 Members | 1,717 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,865 IT Pros & Developers. It's quick & easy.

Validate php form using javascript

100+
P: 250
I have a web site with several web pages. They are having different number of variables. eg: first page having 4 variables in the form(Name, Phone, ID, Gender)
second page having 10 variables in the form(eg: Name, Age, Time, etc.)
I want to validate each and every variable. So how can I do that? I found this JavaScript.But in this case for each and every variable I have to write a function.Eg:for each and every variable i have to rewrite the code to check whether the field is empty
Please tell me is there any easy way to do this?

Expand|Select|Wrap|Line Numbers
  1. function validateFormOnSubmit(theForm) {
  2. var reason = "";
  3.  
  4.   reason = reason+validateUsername(theForm.username);
  5.   reason = reason+validatePassword(theForm.pwd);
  6.   reason = reason+validateEmail(theForm.email);
  7.   reason = reason+validatePhone(theForm.phone);
  8.   reason = reason+validateEmpty(theForm.from);
  9.  
  10.   if (reason != "") {
  11.     alert("Warning!:\n" + reason);
  12.     return false;
  13.   }
  14.  
  15.   return true;
  16. }
  17.  
  18. function validateEmpty(fld) {
  19.     var error = "";
  20.  
  21.     if (fld.value.length == 0) {
  22.         fld.style.background = 'Yellow'; 
  23.         error = "The required field has not been filled in.\n"
  24.     } else {
  25.         fld.style.background = 'White';
  26.     }
  27.     return error;  
  28. }
  29.  
  30. function validateUsername(fld) {
  31.     var error = "";
  32.     var illegalChars = /\W/; // allow letters, numbers, and underscores
  33.  
  34.     if (fld.value == "") {
  35.         fld.style.background = 'Yellow'; 
  36.         error = "You didn't enter a username.\n";
  37.     } else if ((fld.value.length < 5) || (fld.value.length > 15)) {
  38.         fld.style.background = 'Yellow'; 
  39.         error = "The username is the wrong length.\n";
  40.     } else if (illegalChars.test(fld.value)) {
  41.         fld.style.background = 'Yellow'; 
  42.         error = "The username contains illegal characters.\n";
  43.     } else {
  44.         fld.style.background = 'White';
  45.     }
  46.     return error;
  47. }
  48.  
  49. function validatePassword(fld) {
  50.     var error = "";
  51.     var illegalChars = /[\W_]/; // allow only letters and numbers 
  52.  
  53.     if (fld.value == "") {
  54.         fld.style.background = 'Yellow';
  55.         error = "You didn't enter a password.\n";
  56.     } else if ((fld.value.length < 7) || (fld.value.length > 15)) {
  57.         error = "The password is the wrong length. \n";
  58.         fld.style.background = 'Yellow';
  59.     } else if (illegalChars.test(fld.value)) {
  60.         error = "The password contains illegal characters.\n";
  61.         fld.style.background = 'Yellow';
  62.     } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
  63.         error = "The password must contain at least one numeral.\n";
  64.         fld.style.background = 'Yellow';
  65.     } else {
  66.         fld.style.background = 'White';
  67.     }
  68.    return error;
  69.  
  70. function trim(s)
  71. {
  72.   return s.replace(/^\s+|\s+$/, '');
  73. }
  74.  
  75. function validateEmail(fld) {
  76.     var error="";
  77.     var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
  78.     var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
  79.     var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
  80.  
  81.     if (fld.value == "") {
  82.         fld.style.background = 'Yellow';
  83.         error = "You didn't enter an email address.\n";
  84.     } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
  85.         fld.style.background = 'Yellow';
  86.         error = "Please enter a valid email address.\n";
  87.     } else if (fld.value.match(illegalChars)) {
  88.         fld.style.background = 'Yellow';
  89.         error = "The email address contains illegal characters.\n";
  90.     } else {
  91.         fld.style.background = 'White';
  92.     }
  93.     return error;
  94. }
  95.  
  96. function validatePhone(fld) {
  97.     var error = "";
  98.     var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    
  99.  
  100.    if (fld.value == "") {
  101.         error = "You didn't enter a phone number.\n";
  102.         fld.style.background = 'Yellow';
  103.     } else if (isNaN(parseInt(stripped))) {
  104.         error = "The phone number contains illegal characters.\n";
  105.         fld.style.background = 'Yellow';
  106.     } else if (!(stripped.length == 10)) {
  107.         error = "The phone number is the wrong length. Make sure you included an area code.\n";
  108.         fld.style.background = 'Yellow';
  109.     }
  110.     return error;
  111. }
  112.  
Jun 11 '09 #1
Share this Question
Share on Google+
5 Replies


Dormilich
Expert Mod 5K+
P: 8,639
there is not much opportunity to make it easier, the main reason is that each field requires different verification algorithms.

nevertheless there is one point to put the lever in… you have 3 tests, that are common to all functions
  • empty value test
  • value length test
  • illegal character test
further if a test fails, the style of the element is changed similarly.

you could prepare some objects (one for each field) which use the same method but use the according properties (which you have to define beforehand)

NOTE: <input> elements may contain an attribute (maxlength) limiting the input length

rough sketch
Expand|Select|Wrap|Line Numbers
  1. // holds the functions to use for verification
  2. // this is passed via inheritance to your object constructor
  3. basemethods = {
  4.   short : function(x) {
  5.     if (this.elem.value.length < x) {
  6.       this.elem.style.background = 'Yellow';
  7.       this.hasError = true;
  8.       return this.error[0];
  9.     }
  10.     this.hasError = false;
  11.     return "";
  12.   },
  13.   illegal : function() {
  14.     if (this.illegalChars.test(this.elem.value)) {
  15.       this.elem.style.background = 'Yellow';
  16.       this.hasError = true;
  17.       return this.error[1];
  18.     }
  19.     this.hasError = false;
  20.     return "";
  21.   },
  22.   reset : function() {
  23.     if (!this.hasError) this.elem.style.background = "white";
  24.   }
  25. };
  26.  
  27. // object constructor
  28. function CheckField(name) {
  29.   this.hasError = false;
  30.   this.elem = document.theForm[name];
  31. }
  32.  
  33. // inheriting the basemethods, discussed elsewhere
  34. CheckField.extends(basemethods);
  35.  
  36. // now for the funny part
  37. // checking Username
  38. var user = new CheckField("username");
  39. user.errMsg = ["The username is the wrong length.\n", "The username contains illegal characters.\n"];
  40. user.illegalChars = /\W/;
  41.  
  42. // execute the functions
  43. reason += user.short(5) + user.illegal();
  44. user.reset();
  45.  
Jun 11 '09 #2

100+
P: 250
hello Dormilich,
How can I pass the form values to this javascript? I didn't get this.
Jun 15 '09 #3

Dormilich
Expert Mod 5K+
P: 8,639
@ghjk
you don't need to pass them yourself, the values are passed automaticly. once you create the object(s), these objects will know themselves how to get the values.

this is when you pass the fields (and along with the fields, their values):
Expand|Select|Wrap|Line Numbers
  1. var user = new CheckField("username"); // the username field
  2. var pass = new CheckField("password"); // the password field
a more detailed explanation.
Expand|Select|Wrap|Line Numbers
  1. // object constructor
  2. function CheckField(name) {
  3.   this.hasError = false;
  4.   this.elem = document.theForm[name];
  5. }
  6.  
  7.  
  8. // another way to add the function to the object
  9. // but the way it works is the same
  10. CheckField.prototype.short = function(x) {
  11.     if (this.elem.value.length < x) {
  12.       this.elem.style.background = 'Yellow';
  13.     }
  14. }
when you create the object (i.e. start the validation)
Expand|Select|Wrap|Line Numbers
  1. var user = new CheckField("username");
the Function (Constructor) is executed. the keyword "this" inside the function refers to the current object (the object we're creating right now). essentially 2 things are done:
1) create an object property named "hasError" and set it to false
2) create an object property named "elem" and store there the reference to the field you want to check. document.theForm.username is the same as document.theForm["username"]. we will use this "short cut" (this.elem = document.theForm.username) to access this input element later on.
Expand|Select|Wrap|Line Numbers
  1. // the field
  2. <input name="username" size="12">
  3.  
  4. // the object
  5. var user = new CheckField("username");
now user.elem points to the username field.

after that, we're setting several other properties (like the error messages and illegal character tests, because they are different for every field).

making the minimum length test:
Expand|Select|Wrap|Line Numbers
  1. var reason += user.short(5)
execute the short() method of the user object and append the returning string to the variable reason.
we test if the field value (this.elem.value = document.theForm.username.value) is larger than the given number (5). the crucial point is, whenever we use this.elem.value, it points to the field, we specified when constructing the object.
Expand|Select|Wrap|Line Numbers
  1. var user = new CheckField("username"); // the username field
  2. var pass = new CheckField("password"); // the password field
using "this" we can refer to the object we want, without having to know the exact name of this field in the first place. when constructing the object, we define what "this" shall be.

a note about methods and functions:
methods are functions, that exclusively belong to an object (i.e. you must call the via objectname.methodname(), thus cannot be called without their object.)
one of the advantages of objects is that the object methods can use the object properties (objectname.propertyname), so you do not need to pass every variable value you need through the call.
Expand|Select|Wrap|Line Numbers
  1. function validateEmpty(fld)
  2. {
  3.     if (fld.value) …
  4. }
  5.  
  6. validateEmpty(document.theForm.username);
vs.
Expand|Select|Wrap|Line Numbers
  1. method validateEmpty() // that's not correct syntax, but you know, what I mean
  2. {
  3.     if (this.elem.value) …
  4. }
  5.  
  6. user.validateEmpty();
Jun 15 '09 #4

100+
P: 250
Thanks for your help Dormilich. I tried. But it is not working. This is my code. Can you please tell me where I went wrong?
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2.  
  3. function validateFormOnSubmit(theForm) {
  4. var reason = "";
  5. basemethods = {
  6.   short : function(x) {
  7.     if (this.elem.value.length < x) {
  8.       this.elem.style.background = 'Yellow';
  9.       this.hasError = true;
  10.       return this.error[0];
  11.     }
  12.     this.hasError = false;
  13.     return "";
  14.   },
  15.   illegal : function() {
  16.     if (this.illegalChars.test(this.elem.value)) {
  17.       this.elem.style.background = 'Yellow';
  18.       this.hasError = true;
  19.       return this.error[1];
  20.     }
  21.     this.hasError = false;
  22.     return "";
  23.   },
  24.   reset : function() {
  25.     if (!this.hasError) this.elem.style.background = "white";
  26.   }
  27. };
  28.  
  29. // object constructor
  30. function CheckField(name) {
  31.   this.hasError = false;
  32.   this.elem = document.theForm[name];
  33. }
  34.  
  35. // inheriting the basemethods, discussed elsewhere
  36. CheckField.extends(basemethods);
  37.  
  38. // now for the funny part
  39. // checking Username
  40. var user = new CheckField("FullName");
  41. user.errMsg = ["The username is the wrong length.\n", "The username contains illegal characters.\n"];
  42. user.illegalChars = /\W/;
  43.  
  44. // execute the functions
  45. reason += user.short(5) + user.illegal();
  46. user.reset();
  47.  
  48. }
  49.  
  50. </script>
  51. <table>
  52. <form action="test.php" method="post" name="myform"  onSubmit="return validateFormOnSubmit(this);" >
  53.                   <tr>
  54.                     <td height="24" colspan="3" ><!--DWLayoutEmptyCell-->&nbsp;</td>
  55.                 </tr>
  56.                   <tr>
  57.                     <td height="24" >Full Name*</td>
  58.                     <td colspan="2"><input type="text" name="FullName"  size="40"/></td>
  59.                   </tr>
  60.  
  61.                   <tr>
  62.                     <td>Gender</td>
  63.                     <td width="69"><input name="Gender" type="radio" value="1" /> Male</td>
  64.  
  65.                     <td width="297"  ><input name="Gender" type="radio" value="2" />Female&nbsp;</td>
  66.                   </tr>
  67.  
  68.                   <tr>
  69.                     <td>Phone Number</td>
  70.                     <td colspan="2"><input type="text" name="PhoneNumber" /></td>
  71.                   </tr>
  72.                   <tr>
  73.                     <td>Mobile Number</td>
  74.                     <td colspan="2"><input type="text" name="MobileNumber" /></td>
  75.                   </tr>
  76.                   <tr>
  77.                     <td>Email Address</td>
  78.                     <td colspan="2"><input type="text" name="EmailAddress" /></td>
  79.                   </tr>
  80.                   <tr>
  81.                     <td>Address</td>
  82.                     <td colspan="2"><input type="text" name="Address" size="40" /></td>
  83.                   </tr>
  84.  
  85.                   <tr>
  86.                     <td>&nbsp;</td>
  87.                     <td colspan="2" align="right">
  88.                     <input name="Submit" value="Submit" id="Submit" type="button"  alt="add" height="30"  width="73" />
  89.                     <input name="Cancel" value="Cancel" id="Cancel"  type="button"  alt="add" height="30"  width="73"/>                     </td>
  90.                   </tr>
  91.                   </form>
  92.                 </table>
Jun 16 '09 #5

Dormilich
Expert Mod 5K+
P: 8,639
@ghjk
well, I said the code was a sketch (to demonstrate the possibility). we need to do some things before this can actually be called working code.

first of all, the code doesn't belong inside another function, this will screw up things heavily.

now I'd rather use prototype (see post #4) than extends() (this method would have to be defined beforehand)

EDIT: I see, we're accessing the form elements differently. this can be resolved, though it needs discussion how. (dynamic or static access?)

there is no validation result output

some base code we could work on
Expand|Select|Wrap|Line Numbers
  1. // object constructor
  2. function CheckField(name) {
  3.   this.reason = "";
  4.   this.elem = document.forms[0].elements[name];
  5. }
  6.  
  7. // adding method short
  8. CheckField.prototype.short = function(x)
  9. {
  10.     if (this.elem.value.length < x) 
  11.     {
  12.       this.elem.style.background = "yellow";
  13.       this.reason += this.error[0];
  14.     }
  15.     return this; // that's used for chaining, you'll see in a moment
  16. }
  17.  
  18. // adding method illegal
  19. CheckField.prototype.illegal = function()
  20. {
  21.     if (this.illegalChars.test(this.elem.value)) 
  22.     {
  23.       this.elem.style.background = "yellow";
  24.       this.reason += this.error[1];
  25.     }
  26.     return this;
  27. }
  28.  
  29. // adding method show
  30. CheckField.prototype.show = function()
  31. {
  32.     if (this.reason) alert(this.reason);
  33.     return this;
  34. }
  35.  
  36. // adding method reset
  37. CheckField.prototype.reset = function()
  38. {
  39.     if (!this.hasError) this.elem.style.background = "white";
  40.     this.reason = "";
  41. }
Expand|Select|Wrap|Line Numbers
  1. var user = new CheckField("username");
  2. // …
  3. // that's called chaining
  4. user.short(5).illegal().show().reset();
Jun 16 '09 #6

Post your reply

Sign in to post your reply or Sign up for a free account.