Search code examples
phpvalidationonfocus

Alter existing validation to accommodate onfocus?


Familiar with creating textfields in a form like this example:-

Name  :<input type="text" name="visitor" /><br /><br />
Email :<input type="text" name="visitormail" /><br /><br />
Phone :<input type="text" name="visitorphone"/><br /><br />

and validating same as in this type of example:-

$vname = $_GET["visitor"];
$vemail = $_GET["visitormail"];
$vphone = $_GET["visitorphone"];

    // VALIDATION INTRODUCTION - THESE ARE THE FORM FIELDS THAT WE REQUIRED THE VISITOR TO FILL IN  
        if(empty($vname) 
        || empty($vemail) 
        || empty($vphone)) 
        { 
        echo "<h2>Go Back and fill in all fields  </h2>\n";
        die ("Use the Go Back button !! ");
        }
        if(!$vemail == "" && (!strstr($vemail,"@") || !strstr($vemail,"."))) 
        {
        echo "<h2>Go Back and enter a valid E-mail Address</h2>\n";
        die ("Use the Go Back button !!");  
        }

The above script works....see this image! Alternate form layout

The Question I have is ???

When the form is created with onfocus textfields as in the following example:-

<input type="text" name="visitor" value="NAME" size="23" onfocus="if (this.value == 'NAME') {this.value = '';}" onblur="if (this.value == '') {this.value = 'NAME';}">

....the above validation no longer works as there is already an entry in the textfield!

Can the above validation be adopted for use in the new onfocus situation?


Solution

  • The simplest way would be altering your current script's if statement like so:

    if((empty($vname) || trim(strtolower($vname)) == 'name')
    || (empty($vemail) || trim(strtolower($vemail)) == 'email') 
    || (empty($vphone) || trim(strtolower($vphone)) == 'phone'))
    

    That should get the job done if you are happy with your current script, but over all you could do a lot better when it comes to your validation as it seems fairly error prone and doesn't seem that user friendly right now - Then again it is an example script so perhaps that's on purpose.

    Anyway, like I said, that would be the simplest way with your current script, although not the best way by any means.