Validate number of characters of username

-1

I have the following validation for the username:

if (empty($_POST["username"])) {
  $nameErr = "Username:Escolha um username.";
} else {
  $uname = test_input($_POST["username"]);
  $v1 = 'ok';
  if (!ereg("(^[a-zA-Z0-9]+([a-zA-Z\_0-9\.-]*))$", $_POST["username"])) {
    $v1 = 'ko';
    $nameErr = "Username:Somente letras e números.";
  }
}

This way I can successfully validate a username that contains letters or numbers or if the field is blank. But how can I validate the number of characters?

    
asked by anonymous 15.03.2016 / 17:32

2 answers

2

To limit the number of characters you can use the maxlength attribute in the input;

<input maxlength="7">

But you ask how to validate the character numbers, so ... You can count the content of the input using the strlen () function. Here's an example below:

$max = 7;
$validar = strlen($_POST["username"]);

if ($validar > $max) {
    return FALSE;
}
else {
    return TRUE;
}
    
15.03.2016 / 17:45
0

With maxlength you can limit direct in html.

Example:

<input type="text" maxlength="5">
    
15.03.2016 / 17:37