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 />";
        }

Link to comment
Share on other sites

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

 

Two things.  First, the email filter considers even _@d.c 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 />";
             }
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.