Search code examples
phpformsvalidationuser-registration

PHP validation form problems linking statements


I have a registration form on my website and need to validate the input before creating the account. I have read that javascript validation can be easily disabled so I have opted for php.

I am having issues linking the different validations using 'and' not quite sure what is going wrong.

if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
                    // Return Error - Invalid Email
                    $msg = 'Please enter a valid email address.';
                } and (!preg_match("/\S+/", $firstname)){
      // Return Error - Firstname blank
                    $msg = 'Please enter your first name.';
  } and (!preg_match("/\S+/", $lastname)){
      // Return Error - Lastname blank
                    $msg = 'Please enter your last name.';
  }(!preg_match("/.{6,}/", $password)){
  // Return Error - password short
                    $msg = 'The password entered is too short. Please use 6 or more characters.';
  }

                else{ //submit form

Is there anything I am missing from the validation that a more experienced coder would use?

Hope you can help a newbie like me...


Solution

  • I didn't check your Regular expressions, but here is a redefined version of your code:

    $msg ="";
    if(!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
        // Return Error - Invalid Email
        $msg = 'Please enter a valid email address.';
    }else if(!preg_match("/\S+/", $firstname)){
        // Return Error - Firstname blank
        $msg = 'Please enter your first name.';
    }else if(!preg_match("/\S+/", $lastname)){
        // Return Error - Lastname blank
        $msg = 'Please enter your last name.';
    }else if((!preg_match("/.{6,}/", $password))){
        // Return Error - password short
        $msg = 'The password entered is too short. Please use 6 or more characters.';
    }else if($msg == ""){
    
    //Submit form
    

    This is a very simple way of doing things, but I recommend taking a few tutorials of validating techniques register forms next time.
    Here are a few good tutorials:
    http://www.smashingmagazine.com/2009/07/07/web-form-validation-best-practices-and-tutorials/
    Video part 1:
    http://www.youtube.com/watch?v=t8ehovDeMuU
    Video part 2:
    http://www.youtube.com/watch?v=FlwlpRQo6II