How to consume validation function?

Asked

Viewed 68 times

3

For didactic reasons, I created a php to validate 3 fields, the function is in the file validate.php :

<?php
/**
 * Created by PhpStorm.
 * User: Jorge
 * Date: 01/06/2018
 * Time: 10:40
 */


function valida($nome, $senha, $email) {

$error = [
        'nome' => 'Não é permitido caracteres especiais nem espaços em branco!',
        'senha' => 'Não é permitido caracteres especiais nem espaços em branco!',
        'email' => 'E-mail incorreto'
       ];
if (!preg_match("/^[a-zA-Z ]*$/", $nome)) {
    $error["nome"];
    exit;
}

if (!preg_match("/^[a-zA-Z ]*$/", $senha)) {
    $error["senha"];
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error["email"];
    exit;
}

 return $error;
}

In my controller I am using it in the following way, but I know it is not correct:

<?php
/**
 * Created by PhpStorm.
 * User: Jorge
 * Date: 30/05/2018
 * Time: 17:36
 */

require "../models/Connection.php";
require "validate.php";

$errorNome = '';
$errorSenha = '';
$errorEmail = '';
if (isset($_POST["username"]) && !empty($_POST["username"])) {
    $user = $_POST["username"];
    $email = $_POST["email"];
    $pass = password_hash($_POST["password"], PASSWORD_DEFAULT);

    if (valida($user, $pass, $email)) {
       $errorNome = $error["nome"];
       $errorPass = $error["senha"];
       $errorEmail = $error["email"];
       header("location: ../views/add.php");
    }
    else {

    $pdo = $pdo->prepare("INSERT INTO users (nome, email, senha) VALUES (?, ?, ?)");
        $pdo->bindParam(1, $user);
        $pdo->bindParam(2, $email);
        $pdo->bindParam(3, $pass);
        $pdo->execute();

        if ($pdo->rowCount() > 0) {
            echo "sucesso!";
        }
    }
}

In the view is as follows:

 require "../controllers/addUserController.php";
?>
<html>
    <head>

    </head>
    <body>
        <form action="../controllers/addUserController.php" method="POST">
            <input type="text" placeholder="Username" name="username"> <span> <?=$errorNome?> </span>
            <input type="text" placeholder="E-mail" name="email"> <span> <?=$errorEmail?> </span>
            <input type="password" placeholder="Password" name="password"> <span> <?=$errorSenha?> </span>
            <input type="submit" value="Cadastrar">
        </form>
    </body>
</html>

My question is, how do I allow the insertion in the bank only if everything is correct as defined in the function? And if any field is wrong, as I do to show the error message?

Is this the right way to perform a check? If not, what would be a good option?

Thank you for your attention.

  • This example shown works (it even shows the error messages)?

  • @Juven_v no, is not displayed.

1 answer

2

Some adaptations are necessary for your example to work the way it is organized. First its function valida() should return different things, whether or not there are errors, an example would be:

php validity.

<?php

/**
 * @return string|null caso haja algum erro de validação retorna
 * um array de strings descrevendo os erros 
 * é retornado, caso não haja erros de validação, retorna null;
 * 
*/
function valida($nome, $senha, $email) {

    $error = [
            'nome' => 'Não é permitido caracteres especiais nem espaços em branco!',
            'senha' => 'Não é permitido caracteres especiais nem espaços em branco!',
            'email' => 'E-mail incorreto'
           ];

    $errosEncontrados = [];

    if (!preg_match("/^[a-zA-Z ]*$/", $nome)) {
        $errosEncontrados['nome'] = $error["nome"];
    }

    if (!preg_match("/^[a-zA-Z ]*$/", $senha)) {
        $errosEncontrados['nome'] = $error["senha"];
    }

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $errosEncontrados['nome'] = $error["email"];
    }

    //verifica o tamanho do vetor $errosEncontrados
    if(count($errosEncontrados) > 0){
        return $errosEncontrados;
    }

    return null;
}

With these changes in the validation function it is possible to verify in the controller whether the fields passed the validation or not. In the controller you need to make some changes (comments have more details):

in your controller.php

<?php
//......
$pass = password_hash($_POST["password"], PASSWORD_DEFAULT);

    //vetor com os erros retornados pela função valida
    //ou null caso não existam
    $erros = valida($user, $pass, $email);
    if ($erros !== null) {
       $errorNome = $errors["nome"];
       $errorPass = $errors["senha"];
       $errorEmail = $errors["email"];
       //se você fizem um header location, essas variaveis não existiram 
       //mais na nova requisição.
       //header("location: ../views/add.php");

       //é mais adequado usar um require ou include, nesse caso
       //nada mais deveria ser impresso, além do que está dentro de add.php
       require '../views/add.php';
       //então faça um exite para garantir que apenas o conteudo do 
       //arquivo incluido seja retorndado para o navegador
       exit;
    }
    else {

    $pdo = $pdo->prepare("INSERT INTO users (nome, email, senha) VALUES (?, ?, ?)");
        $pdo->bindParam(1, $user);
        $pdo->bindParam(2, $email);
        $pdo->bindParam(3, $pass);
        $pdo->execute();
//.......

Here there were only two changes, one to check for validation errors, and the other related to the Location header, which would not work as expected.

In your view should work as expected unless the file add.php is called without the variables used in it having been declared before. To avoid this possible problem, simply change the occurrences of <?=$errorEmail?> for .

An alternative would be to use some validation library, such as the respect

  • In place of $errors shouldn’t be $errosEncontrados? Or is that msm?

  • $errosEncontrados only visible within the function valida(), scope issue. The value returned by the function validates is that it is stored in the variable $erros, and is visible in the controller.

Browser other questions tagged

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