Validate text fields in php

0

I'm doing a form in php and I need to validate that the fields are not empty. However, when writing EMPTY SPACES in the input, my function is returning a true value. Then the concrete question would be: How to validate that an input does not start with empty spaces but that it accepts them? For example, for the field Name: Jesús Adrían (It is a name composed of two names and it has a space in between).

Currently my role is this:

public static function validarTexto($texto){
        if($texto==""){
            return false;
        }else{
            $patron = '/^[a-zA-Z, ]*$/';
            if(preg_match($patron,$texto)){
                return true;     
            }else{
                return false;
            }
        }

    }

Here is an example of what happens to me:

Thanks for your timely help. Greetings.

    
asked by Neftali Acosta 17.01.2018 в 04:35
source

5 answers

1

Well, I "immersed myself a bit more into the PHP documentation and found the function I needed.

(PHP 4, PHP 5, PHP 7)

trim - Remove blank space (or other characters) from the beginning and end of the string.

This function returns a string with the blanks removed from the start and end of the str. without the second parameter, trim () will remove these characters:

"" (ASCII 32 (0x20)), single space.

"\ t" (ASCII 9 (0x09)), tabulation.

"\ n" (ASCII 10 (0x0A)), line break.

"\ r" (ASCII 13 (0x0D)), carriage return.

"\ 0" (ASCII 0 (0x00)), byte NUL.

"\ x0B" (ASCII 11 (0x0B)), vertical tab.

More details: link

At the end my function was like this:

public static function validarTexto($texto){
        $texto = trim($texto);
        if($texto=="" && trim($texto)==""){
            return false;
        }else{
            $patron = '/^[a-zA-Z, ]*$/';
            if(preg_match($patron,$texto)){
                return true;   
            }else{
                return false;
            }
        }   
    }
    
answered by 17.01.2018 / 04:50
source
1

This may help you:

if(!isset($_POST['mi_campo']) || strlen(trim($_POST['mi_campo'])) == 0){
    die('El campo es vacio'); //aquí lo personalizas
}

We check if the variable is set and that its size is not zero.

    
answered by 17.01.2018 в 04:53
0

The first filtering of a text entry would pass through the trim () function, with this the blank spaces are eliminated at the beginning and end of a text string, all its content if only there are spaces, with which we obtain a chain without extra spaces in the first case and an empty string in the second (no useful content was introduced) that allows us to continue with the logic of the validations.

Your cleaning method, rewritten would look like this:

public static function validateStrContent($str)
{
    $str = trim($str);
    if ($str !== '') {
        $pattern = '/^[a-zA-Z, ]*$/';
        if (preg_match($pattern, $str)) {
            return true;   
        }
    }

    return false;   
}


If we add typing, recommended for PHP7, it would be:

public static function validateStrContent(string $str): bool
{
    $str = trim($str);
    if ($str !== '') {
        $pattern = '/^[a-zA-Z, ]*$/';
        if (preg_match($pattern, $str)) {
            return true;   
        }
    }

    return false;   
}
    
answered by 05.01.2019 в 09:41
0

you can use the following:

public static function validarTexto($texto){
return !empty(trim($texto));
}

PHP's native trim function is used to remove spaces at the edges of your text string. This means, remove a space at the beginning and end of the chain.

The PHP empty native function returns true (boolean) if the value it receives is empty.

Reference of both functions: link link

    
answered by 08.01.2019 в 20:03
-2

The solution to the problem is described below:

// Hay que tomar en cuenta que el usuario puede ingresar
// caracteres en blanco por lo que se recomienda eliminarlos
// todos utilizando la función «str_replace»:
public static function validarTexto ($texto) {
    // Se eliminan todos los caracteres de tipo espacios
    // en blanco:
    $texto = str_replace(" ", "", $texto);

    // Se valida ahora que el campo se encuentre
    // vacío.
    if (empty($texto)) {
        // Si se encuentra vacío, entonces retornará 
        // un «false» (falso) y terminará la ejecución
        // del código dentro de la función:
        return false;
    }

    // Retorna «true» (verdadero) si el texto contiene caracteres válidos:
    return true;
}

A simplified version of the code (without the use of comments) is:

public static function validarTexto ($texto) {
    $texto = str_replace(" ", "", $texto);
    if (empty($texto)) {
        return false;
    }
    return true;
}
    
answered by 05.01.2019 в 08:29