Answer the question
In order to leave comments, you need to log in
How to properly validate the email field in PHP in a form?
Hello everybody!
Please help me figure out the correct email validation.
There is an HTML form (the example shows part of the email form):
<label>E-mail:</label>
<input id="input5" type="text" size="25" name="email" value= "<?php echo $email ?>">
<span class="error">* <?php if(isset($errors['email'])) { echo $errors['email']; }?></span>
<br><br>
, которая обрабатывается PHP.
// пример обработки поля email. другие поля обрабатываются таким же образом:
...
if (empty($_POST["email"])) {
$errors['email'] = "Не заполнено обязательное поле";
} else {
$email = test_input($_POST["email"]);
}
...
Answer the question
In order to leave comments, you need to log in
For those interested, here is the solution:
if (empty($_POST["email"])) {
$errors['email'] = "Не заполнено обязательное поле";
} elseif ( filter_var($_POST["email"], FILTER_VALIDATE_EMAIL) === false) {
$errors['email'] = "формат почтового ящика неправильный";
} else {
$email = test_input($_POST["email"]);
}
And this is yours, excuse me, what kind of sample is this? Where does it come from and how do you plan to check something on it? You need to check the regular expression already when submitting the form. That is, when the user clicked the "Submit" button on the form.
$errors = [];
if (!preg_match ('/[\.a-z0-9_\-]+[@][a-z0-9_\-]+([.][a-z0-9_\-]+)+[a-z]{1,4}/i', $_POST['email']))
$errors[] = 'Не валидный email';
if ($errors) {
$content = 'При отправке формы произошли следующие ошибки:<br/><br/>';
foreach ($errors as $error) $content .= $error.'<br/>';
echo $content;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question