Last active
May 31, 2019 23:03
-
-
Save erikfig/58af2c2afd552e7f21a36d13ec1230e9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Document</title> | |
</head> | |
<body> | |
<form action="result.php" method="post"> | |
<input type="text" name="name"> | |
<input type="submit" value="salvar"> | |
</form> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$name = filter_input(INPUT_POST, 'name'); // pego o valor enviado pelo formulário | |
try { | |
if (!$name) { | |
throw new InvalidArgumentException('Nome não pode ficar em branco'); | |
} | |
preg_match('/\s/', $name, $matches); // pego os espaços | |
if (count($matches) > 0) { // verifico se tem algum (zero ou mains) | |
throw new InvalidArgumentException('Nome não pode conter espaços'); | |
} | |
echo 'Ok, valor correto'; | |
} catch(InvalidArgumentException $e) { | |
// exibo a mensagem de erro | |
http_response_code(422); // erro 422 Unprocessable Entity, só para adicionar o header correto | |
$error_message = [ | |
'Erro de validação:', | |
$e->getMessage() | |
]; | |
echo implode(' ', $error_message); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment