Jump to content

Regexp or Filters for PHP form validation


john2020

Recommended Posts

Hi,

 

I use a mixture of both. For usernames/passwords i use regex and for email i use php filters basic but does it's job.

 

Example:

 

For usernames i use the following regex:

 

// username regular expression
define('USERNAME_REGEX', '/^[a-z][\w\.\*\-\_]{2,14}$/i');

 

For emails i use PHP filter:

 

filter_var( $email , FILTER_VALIDATE_EMAIL)

 

I use preg_match() and do error checking like this, depending on what i am wanting to do/acheive.

 

     if ( !preg_match(constant("USERNAME_REGEX"), $username)) {
             $error .= "Please enter a username. Use 3 to 15 characters and start with a letter. You may use
             letters, numbers, hyphen, asterisk, underscores and dot (.) <br />";
             }

        if (!empty( $email) && !filter_var( $email , FILTER_VALIDATE_EMAIL)) {
            $error .= "Your email address is not valid <br />";
        }

Thank you, guys!  It's good to know that they complement each other.

 

Two things.  First, the email filter considers even [email protected] to be a valid email address.  Second, there must be some newbie error but I can't get this to work:

if ($_POST["Submit"]) {
define('USERNAME_REGEX', '/^[a-z][\w\.\*\-\_]{2,14}$/i');
$username = $_POST["username"];
     if ( !preg_match(constant("USERNAME_REGEX"), $username)) {
             $error .= "Please enter a username. Use 3 to 15 characters and start with a letter. You may use
             letters, numbers, hyphen, asterisk, underscores and dot (.) <br />";
             }
}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.