Validate username character number

Asked

Viewed 96 times

-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 empty. But how do I validate the number of characters?

  • 1

    uses maxlength, the html attribute

  • 3

    @Gabrielrodrigues hum.. then the guy takes away the developer’s tools, and the validation goes to space.

  • @Wallacemaxters exactly.

2 answers

2


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

<input maxlength="7">

But you ask how to validate the number of characters, so... You can count the input content using the function strlen(). Follow an example below:

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

if ($validar > $max) {
    return FALSE;
}
else {
    return TRUE;
}
  • 2

    I would use the mb_strlen ;). Just a hint.

  • @Wallacemaxters if the page is in ISO-8859-1 can be problematic. Especially if you take characters like "Ç", "Ã", etc. that will be interpreted as UTF-8

  • @Bacco is complicated this. If the username it’s just ascii, so it’s cool, right.

  • 1

    @Wallacemaxters would ideally warn Chris in response that if encoding is UTF, use mb_strlen, if ISO-8859-1 or similar, use strlen :) - As for HTML5, I find it hard not to have a native "minlength".

0

With maxlength you can limit directly in html.

Example:

<input type="text" maxlength="5">

  • Easy Thank you very much, I did not remember this property. solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.