Knowing if there are blanks

Asked

Viewed 3,915 times

4

Good community! I have the following doubt. How can I alert the user that there are blanks in the field username?

This is 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."; 
 }

}

  • 1

    Form validation? Have you ever considered using javascript? This type of server-side validation only wastes request and processing.

  • Thank you for replying @Diegofelipe. Yes is registration form validation. In this case, the field "username". I do not want spaces in username... I’m by the same php

  • 2

    @Diego Felipe, The server-side validation should always be performed independent of client-side validation.

  • Modify your question, @David Concha, because the way you’re different from what you said. A blank field is very different from removing spaces in a specific field.

  • 2

    @Diegofelipe validation is only on the server side. On the client side you can only do a simple preliminary check, but there is no way to avoid sending inappropriate data.

  • @Danielomine yes, but having validation on the client’s side already avoids many requests simply because one field or another has not been filled in. I see php more to confirm validation(user can disable javascript) or as security that data is actually being passed correctly.

  • @Bacco but you do not agree that it greatly reduces the number of wasted requests because of validation that could be alerted to the user before submitting?

  • 1

    @Diegofelipe I do not agree with the part that you said that "this validation only wastes request and processing", because it is fundamental for data integrity is always that of the server. As band savings and requisition, I agree that pre-validation is good (that part I didn’t even question, incidentally).

Show 3 more comments

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 function trim clears left and right spaces. The function empty check if the field is empty. The function is_null checks if the field is of the type NULL

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

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

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

<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 allow to submit the form before filling in 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!";
}
?>
  • If the entry of the post does not exist, it will trigger an error.

  • 3

    @Diegofelipe will fire one Warning in fact.

  • 1

    I did not want to remove the spaces, but rather alert the user q there are blank spaces in the field username

  • 1

    Check the last example I gave with ereg

  • I used your ereg and still not showing the error that there are spaces. I will analyze my code better.

  • 2

    ereg_ was depreciated in php5.3 and removed in 7.

Show 1 more comment

4

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

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

According to the commentary William Lautert, \s other than white space means other characters like \t\r\n\f\v

  • \s = [ \t\r\n\f\v], I think it should be just ' ' same :D

  • @Guilhermelautert, haha depends on the case, there are people who do not like spaces between lines or remove them from the parentheses funcao ( $param ); then the guy sees a space in the regex and thinks it’s tied and removes it :P.

  • I understand, but I always stress this, because the staff always publicize \s as being ' ', but in fact it is much more, up to "tab vertical" (\v), I don’t even know what that is :P

  • @Guillhermelautert What is a vertical tab? two minutes ago I also did not know haha xD

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. Please be aware. Adapt the example to your needs.

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

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';
    }
?>

Browser other questions tagged

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