Validate php form using javascript

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ghjk
    Contributor
    • Jan 2008
    • 250

    Validate php form using javascript

    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?

    Code:
    function validateFormOnSubmit(theForm) {
    var reason = "";
    
      reason = reason+validateUsername(theForm.username);
      reason = reason+validatePassword(theForm.pwd);
      reason = reason+validateEmail(theForm.email);
      reason = reason+validatePhone(theForm.phone);
      reason = reason+validateEmpty(theForm.from);
          
      if (reason != "") {
        alert("Warning!:\n" + reason);
        return false;
      }
    
      return true;
    }
    
    function validateEmpty(fld) {
        var error = "";
     
        if (fld.value.length == 0) {
            fld.style.background = 'Yellow'; 
            error = "The required field has not been filled in.\n"
        } else {
            fld.style.background = 'White';
        }
        return error;  
    }
    
    function validateUsername(fld) {
        var error = "";
        var illegalChars = /\W/; // allow letters, numbers, and underscores
     
        if (fld.value == "") {
            fld.style.background = 'Yellow'; 
            error = "You didn't enter a username.\n";
        } else if ((fld.value.length < 5) || (fld.value.length > 15)) {
            fld.style.background = 'Yellow'; 
            error = "The username is the wrong length.\n";
        } else if (illegalChars.test(fld.value)) {
            fld.style.background = 'Yellow'; 
            error = "The username contains illegal characters.\n";
        } else {
            fld.style.background = 'White';
        }
        return error;
    }
    
    function validatePassword(fld) {
        var error = "";
        var illegalChars = /[\W_]/; // allow only letters and numbers 
     
        if (fld.value == "") {
            fld.style.background = 'Yellow';
            error = "You didn't enter a password.\n";
        } else if ((fld.value.length < 7) || (fld.value.length > 15)) {
            error = "The password is the wrong length. \n";
            fld.style.background = 'Yellow';
        } else if (illegalChars.test(fld.value)) {
            error = "The password contains illegal characters.\n";
            fld.style.background = 'Yellow';
        } else if (!((fld.value.search(/(a-z)+/)) && (fld.value.search(/(0-9)+/)))) {
            error = "The password must contain at least one numeral.\n";
            fld.style.background = 'Yellow';
        } else {
            fld.style.background = 'White';
        }
       return error;
    } 
    
    function trim(s)
    {
      return s.replace(/^\s+|\s+$/, '');
    }
    
    function validateEmail(fld) {
        var error="";
        var tfld = trim(fld.value);                        // value of field with whitespace trimmed off
        var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
        var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
       
        if (fld.value == "") {
            fld.style.background = 'Yellow';
            error = "You didn't enter an email address.\n";
        } else if (!emailFilter.test(tfld)) {              //test email for illegal characters
            fld.style.background = 'Yellow';
            error = "Please enter a valid email address.\n";
        } else if (fld.value.match(illegalChars)) {
            fld.style.background = 'Yellow';
            error = "The email address contains illegal characters.\n";
        } else {
            fld.style.background = 'White';
        }
        return error;
    }
    
    function validatePhone(fld) {
        var error = "";
        var stripped = fld.value.replace(/[\(\)\.\-\ ]/g, '');    
    
       if (fld.value == "") {
            error = "You didn't enter a phone number.\n";
            fld.style.background = 'Yellow';
        } else if (isNaN(parseInt(stripped))) {
            error = "The phone number contains illegal characters.\n";
            fld.style.background = 'Yellow';
        } else if (!(stripped.length == 10)) {
            error = "The phone number is the wrong length. Make sure you included an area code.\n";
            fld.style.background = 'Yellow';
        }
        return error;
    }
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    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
    Code:
    // holds the functions to use for verification
    // this is passed via inheritance to your object constructor
    basemethods = {
      short : function(x) {
        if (this.elem.value.length < x) {
          this.elem.style.background = 'Yellow';
          this.hasError = true;
          return this.error[0];
        }
        this.hasError = false;
        return "";
      },
      illegal : function() {
        if (this.illegalChars.test(this.elem.value)) {
          this.elem.style.background = 'Yellow';
          this.hasError = true;
          return this.error[1];
        }
        this.hasError = false;
        return "";
      },
      reset : function() {
        if (!this.hasError) this.elem.style.background = "white";
      }
    };
    
    // object constructor
    function CheckField(name) {
      this.hasError = false;
      this.elem = document.theForm[name];
    }
    
    // inheriting the basemethods, discussed elsewhere
    CheckField.extends(basemethods);
    
    // now for the funny part
    // checking Username
    var user = new CheckField("username");
    user.errMsg = ["The username is the wrong length.\n", "The username contains illegal characters.\n"];
    user.illegalChars = /\W/;
    
    // execute the functions
    reason += user.short(5) + user.illegal();
    user.reset();

    Comment

    • ghjk
      Contributor
      • Jan 2008
      • 250

      #3
      hello Dormilich,
      How can I pass the form values to this javascript? I didn't get this.

      Comment

      • Dormilich
        Recognized Expert Expert
        • Aug 2008
        • 8694

        #4
        Originally posted by ghjk
        How can I pass the form values to this javascript? I didn't get this.
        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):
        Code:
        var user = new CheckField("username"); // the username field
        var pass = new CheckField("password"); // the password field
        a more detailed explanation.
        Code:
        // object constructor
        function CheckField(name) {
          this.hasError = false;
          [b]this.elem[/b] = [U]document.theForm[name][/U];
        }
        
        
        // another way to add the function to the object
        // but the way it works is the same
        CheckField.prototype.short = function(x) {
            if ([B]this.elem[/B].value.length < x) {
              [B]this.elem[/B].style.background = 'Yellow';
            }
        }
        when you create the object (i.e. start the validation)
        Code:
        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.theFor m.username is the same as document.theFor m["username"]. we will use this "short cut" (this.elem = document.theFor m.username) to access this input element later on.
        Code:
        // the field
        <input [B]name="username"[/B] size="12">
        
        // the object
        var user = new CheckField("[B]username[/B]");
        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:
        Code:
        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.valu e = document.theFor m.username.valu e) 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.
        Code:
        var user = new CheckField("username"); // the username field
        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.meth odname(), thus cannot be called without their object.)
        one of the advantages of objects is that the object methods can use the object properties (objectname.prop ertyname), so you do not need to pass every variable value you need through the call.
        Code:
        function validateEmpty(fld)
        {
            if (fld.value) …
        }
        
        validateEmpty(document.theForm.username);
        vs.
        Code:
        method validateEmpty() // that's not correct syntax, but you know, what I mean
        {
            if (this.elem.value) …
        }
        
        user.validateEmpty();

        Comment

        • ghjk
          Contributor
          • Jan 2008
          • 250

          #5
          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?
          Code:
          <script type="text/javascript">
          
          function validateFormOnSubmit(theForm) {
          var reason = "";
          basemethods = {
            short : function(x) {
              if (this.elem.value.length < x) {
                this.elem.style.background = 'Yellow';
                this.hasError = true;
                return this.error[0];
              }
              this.hasError = false;
              return "";
            },
            illegal : function() {
              if (this.illegalChars.test(this.elem.value)) {
                this.elem.style.background = 'Yellow';
                this.hasError = true;
                return this.error[1];
              }
              this.hasError = false;
              return "";
            },
            reset : function() {
              if (!this.hasError) this.elem.style.background = "white";
            }
          };
           
          // object constructor
          function CheckField(name) {
            this.hasError = false;
            this.elem = document.theForm[name];
          }
           
          // inheriting the basemethods, discussed elsewhere
          CheckField.extends(basemethods);
           
          // now for the funny part
          // checking Username
          var user = new CheckField("FullName");
          user.errMsg = ["The username is the wrong length.\n", "The username contains illegal characters.\n"];
          user.illegalChars = /\W/;
           
          // execute the functions
          reason += user.short(5) + user.illegal();
          user.reset();
           
          }
          
          </script>
          <table>
          <form action="test.php" method="post" name="myform"  onSubmit="return validateFormOnSubmit(this);" >
          				  <tr>
          				    <td height="24" colspan="3" ><!--DWLayoutEmptyCell-->&nbsp;</td>
          			    </tr>
          				  <tr>
          					<td height="24" >Full Name*</td>
          					<td colspan="2"><input type="text" name="FullName"  size="40"/></td>
          				  </tr>
          				  
          				  <tr>
          					<td>Gender</td>
          					<td width="69"><input name="Gender" type="radio" value="1" /> Male</td>
          					
          				    <td width="297"  ><input name="Gender" type="radio" value="2" />Female&nbsp;</td>
          				  </tr>
          				  
          				  <tr>
          					<td>Phone Number</td>
          					<td colspan="2"><input type="text" name="PhoneNumber" /></td>
          				  </tr>
          				  <tr>
          					<td>Mobile Number</td>
          					<td colspan="2"><input type="text" name="MobileNumber" /></td>
          				  </tr>
          				  <tr>
          					<td>Email Address</td>
          					<td colspan="2"><input type="text" name="EmailAddress" /></td>
          				  </tr>
          				  <tr>
          					<td>Address</td>
          					<td colspan="2"><input type="text" name="Address" size="40" /></td>
          				  </tr>
          				  
          				  <tr>
          					<td>&nbsp;</td>
          					<td colspan="2" align="right">
          					<input name="Submit" value="Submit" id="Submit" type="button"  alt="add" height="30"  width="73" />
          					<input name="Cancel" value="Cancel" id="Cancel"  type="button"  alt="add" height="30"  width="73"/>					 </td>
          				  </tr>
          				  </form>
          				</table>
          Last edited by Dormilich; Jun 16 '09, 07:30 AM. Reason: Please use [code] tags when posting code

          Comment

          • Dormilich
            Recognized Expert Expert
            • Aug 2008
            • 8694

            #6
            Originally posted by ghjk
            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?
            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
            Code:
            // object constructor
            function CheckField(name) {
              this.reason = "";
              this.elem = document.forms[0].elements[name];
            }
            
            // adding method short
            CheckField.prototype.short = function(x)
            {
                if (this.elem.value.length < x) 
                {
                  this.elem.style.background = "yellow";
                  this.reason += this.error[0];
                }
                return this; // that's used for chaining, you'll see in a moment
            }
            
            // adding method illegal
            CheckField.prototype.illegal = function()
            {
                if (this.illegalChars.test(this.elem.value)) 
                {
                  this.elem.style.background = "yellow";
                  this.reason += this.error[1];
                }
                return this;
            }
            
            // adding method show
            CheckField.prototype.show = function()
            {
                if (this.reason) alert(this.reason);
                return this;
            }
            
            // adding method reset
            CheckField.prototype.reset = function()
            {
                if (!this.hasError) this.elem.style.background = "white";
                this.reason = "";
            }
            Code:
            var user = new CheckField("username");
            // …
            // that's called chaining
            user.short(5).illegal().show().reset();
            Last edited by Dormilich; Jun 16 '09, 10:10 AM. Reason: refined code sample

            Comment

            Working...