Skip to content

Instantly share code, notes, and snippets.

@erikfig
Last active May 31, 2019 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erikfig/58af2c2afd552e7f21a36d13ec1230e9 to your computer and use it in GitHub Desktop.
Save erikfig/58af2c2afd552e7f21a36d13ec1230e9 to your computer and use it in GitHub Desktop.
<!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>
<?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