It is not possible to check the emails in the database only using the "HTML API" ( pattern=""
), WEB communication is done via HTTP, p>
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);
}
HTML should be something like:
<form>
<input type="email" pattern="[^@]@[^@]$" required onblur="validateEmail(this)">
<button>Cadastrar</button>
</form>
In the php (it seems that is what you use) would just return a string as 'available' if the email does not exist in the database, or return anything else 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';
}
}