Know if there are any blanks

3

Good community! I have the following doubt. How can I warn the user that there are white spaces in the username field?

Here's how I'm validating username now:

if (empty($_POST["username"])) {
 $nameErr = "Escolha um username.";
   } else {
 $uname = test_input($_POST["username"]);
 $v1='ok';

 if (!preg_match("/^[a-zA-Z-0-9-_]*$/",$uname)) {
   $nameErr = "Somente letras e números."; 
 }
}

The solution was this:

 if ($_SERVER["REQUEST_METHOD"] == "POST") {
 if (empty($_POST["username"])) {
  $nameErr = "Escolha um username.";
   } else {
 $uname = test_input($_POST["username"]);

 // check if name only contains letters and whitespace

 // aqui
 if (!ereg("(^[a-zA-Z0-9]+([a-zA-Z\_0-9\.-]*))$", $_POST["username"]) ) {

   $nameErr = "Somente letras e números."; 
 }

}

    
asked by anonymous 27.01.2016 / 01:31

4 answers

4

Try

<?php
$username = trim($_POST["username"]);

if(empty($username) || is_null($username)){
echo 'Preencha o seu username!';
}else{
echo 'Tudo OK';
}
?>

The trim function clears the left and right spaces. The empty function checks if the field is empty. The is_null function checks if the field is of type NULL

If you want to remove spaces from a field you can do this:

<?php
$username = str_replace(" ", "", trim($_POST["username"]));
//Removerá todos os espaços do username
?>

To get better, always use required in the HTML (of the inputs) tags that you want to be mandatory, eg:

<input type="text" name="username" required>

So when the user submits the form and the field is empty it automatically displays a message for the user to fill in the field, so do not let the form submit before populating that field.

To accept only "normal" characters:

<?php
if (!ereg("^([A-Za-z0-9_-])", $_POST["username"]) ) {
    echo "Não use caracteres especiais nem espaços!";
}
?>
    
27.01.2016 / 01:37
4

In a regular expression, \s means white space. You can change [a-zA-Z-0-9-_] by \s , this will capture.

if(preg_match("/\s*/",$uname)){
   echo 'espaço em branco';
}else{
    echo 'nome válido.';
}

According to Guilherme Lautert's comment, the% w / w% as well as the blank space means other characters like \s

    
27.01.2016 / 02:23
2
if (isset($_POST['username'])) {
    /**
    Aqui remove não somente o caracter de espaço ansi, como também o caracter de espaço multibyte, do idioma japonês.
    */
    $str = mbstr_replace(array(' ', ' '), '', $_POST['username']);

    /**
    Aqui comparamos a string original com a string sanitizada. Se forem diferentes, quer dizer que existia espaços.
    */
    if ($_POST['username'] != $str) {
        echo 'digitou o nome com espaços';
    }
}

The example is purely didactic. Be aware, please. Adapt the example to suit your needs.

To better understand, see this topic that talks about sanitization, filtering, and validation: How to know if the form is sent

    
27.01.2016 / 01:50
1

Try this:

<?php
    //Tira os espaços em branco do começo e do fim
    $username = trim($_POST["username"]);

    if(empty($username) || is_null($username)) {
        echo 'O username não pode ser vazio';
    } else if (strrpos($username, " ") !== false) { //Procura a última ocorrência de espaço
        echo 'Não pode haver espaços no meio do username';
    } else {
        echo 'Username válido';
    }
?>
    
27.01.2016 / 14:26