Is not possible check emails in the database only using the "HTML API" (pattern=""
), in WEB communication is all done via HTTP, so you need a request.
You will need to do this using Ajax for example:
function validateEmail(field)
{
//Se o campo estiver vazio ou desabilitado então não valida
if (field.value == "" || field.disabled) return;
field.disabled = true;
var xhr = new XMLHttpRequest;
xhr.open("GET", "checkEmail.php?email=" + encodeURIComponent(emailField.value), true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseText == 'disponivel') {
alert('Validou');
} else {
alert('Não validou');
}
} else {
alert('Erro HTTP: ' + xhr.status);
}
}
}
xmlhttp.send(null);
}
In HTML it should be something like:
<form>
<input type="email" pattern="[^@]@[^@]$" required onblur="validateEmail(this)">
<button>Cadastrar</button>
</form>
In php (it seems that’s what you use) just return a string as 'available' random email does not exist in the bank, or return anything else chance already exists, an example with mysqli:
checkEmail.php
<?php
if (empty($_GET['email'])) {
die('email vazio');
}
$email = $_GET['email'];
if (!preg_match('#^[^@]+[@][@]+$#', $email)) {
die('formato inválido');
}
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = 'SELECT COUNT(*) as total FROM tabela WHERE email=?';
$stmt = $mysqli->prepare($query);
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->bind_result($total);
while ($stmt->fetch()) {
if ($total > 0) {
echo 'já cadastrado';
} else {
echo 'disponivel';
}
}
in back php and front html+js.
– Jean Freitas
Although the answers are clear about the suggestions and recommendations, the problem is not related to whether it already exists, the problem is only to mark the field as invalid as for example in the image that upei.
– Jean Freitas