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
@Juven_v no, is not displayed.
– Jorge.M