Form Validation

Discussion in 'PHP' started by oo7ml, Jun 18, 2007.

  1. #1
    I have some form validation done, but it's not very good. How do i make sure that users can only use a-z, A-Z, 0-9. Would this help make sure my site is more secure. (there for users would not be able to use special characters)

    Here is the code i have so far:

    // check that username is 5 characters or more
    $username	= $_POST['username'];
    if (strlen($username) > 4){
    
    }
    else {
      die
    
    //email validation - i got this from a script
    
    $email = $_POST['email'];
    
    if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)) {
    
    }
    else {
      die
    PHP:
    how can i make sure that the $username only can have a-z, A-Z, 0-9
     
    oo7ml, Jun 18, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #2
    
    if (!preg_match('/^[a-z0-9]{5,25}$/i', $username))
    {
        // Throw error
    }
    
    PHP:
    The 5 would be the minimum length, and 25 the maximum length. So you can take out the strlen() condition.

    You can also use ctype_alnum(), it's slightly faster than preg_match(), but it doesn't check for the length.

    
    if (!ctype_alnum($username))
    {
        // Throw error
    }
    
    PHP:
     
    nico_swd, Jun 18, 2007 IP
  3. oo7ml

    oo7ml Well-Known Member

    Messages:
    656
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    105
    #3
    K cool, but can you explain what

    {5,25}$/i',
    PHP:
    does in:

    if (!preg_match('/^[a-z0-9]{5,25}$/i', $username))
    {
        // Throw error
    }
    PHP:
    thanks for your help
     
    oo7ml, Jun 18, 2007 IP
  4. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
    #4
    It's part of the regular expression. The {5,25} means that the string must be between 5 and 25 characters long. And the $ marks the end of the string. So that the user can't enter anything behind the 5 to 25 character string. And the i makes the whole search case-insensitive.
     
    nico_swd, Jun 18, 2007 IP
  5. oo7ml

    oo7ml Well-Known Member

    Messages:
    656
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    105
    #5
    Wow, thanks man
     
    oo7ml, Jun 18, 2007 IP