0

I currently have this code below which validates username length only. If none entered it will show error message, if less than 3 characters entered show error message. I want to add an if/else statement that if the user enters special characters like !@#$%^&*()+=/? etc... the only special character is allowed is underscore (_) and hypen (-)... Help me how.

thanks

here's the code i have:

<?php
$serror="";
if (isset($_POST['submit'])) {              
    $username=$_POST['username'];
    $lengt = strlen($username);

    if($lengt == 0){
        $serror=" Please enter account username ";
    }
    else{
        if($lengt < 3 ){            
            $serror=" Please enter valid account username ";
        }
    }
    if($serror==""){
        ob_start();
        echo "Success";
        header("Location:progress.php?username=$username");
        exit;
        ob_end_flush();
    }
    else{}              
}
?>
Mohammad
  • 21,175
  • 15
  • 55
  • 84
james
  • 73
  • 1
  • 9

3 Answers3

0

use preg_match() function

$yourString = "blahblah";
if (preg_match('/^[A-Za-z0-9_-]*$/', $yourString)) {
    #your string is good
} 

remeber preg_match() returns boolean

Ahmad ghoneim
  • 844
  • 7
  • 13
0

Your php script works after the user submits the form. From your tags in the question I assume you can use javascript. With Javascript you catch these errors before the form is submitted.

So, your html input field would fire a script and you can use the onkeypress event to see the value of the keystroke.

The submit button would also have a javascript event to look for min string length, else give warning and not submit form.

Community
  • 1
  • 1
bluepinto
  • 165
  • 9
0

As others already pointed out, you should use regular expressions for this.

Try with the following if-statement (allows a-z, numbers, underscores and hyphens). It also checks that the length is at least 3 characters:

if (!preg_match("/^([\w\-]{3,})$/", $username)) {
    $error = "Not enough chars or there are invalid ones".
}

Read more about preg_match() here

M. Eriksson
  • 13,450
  • 4
  • 29
  • 40