setCustomValidity does not work with Ajax

Asked

Viewed 217 times

2

In a field change event I try to validate a username through an Ajax call. Apparently the setCustomValidity of Html5 does not work with jQuery. I ask for help for anyone who knows javascript.



$("#entrada_usuario").blur(function () {
    var obj = new Object();
    obj.usuario = $("#entrada_usuario").val();
    var parametro = JSON.stringify(obj);
            $.ajax
            (
                {
                    type: "post",
                    url: "validausuario.php",
                    data: parametro,
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (resultado) {
                        if (resultado != 0) {

                            var element = $("#entrada_usuario")[0];
                            element.setCustomValidity('Usuário já existe!');
                            alert(element.checkValidity());
                            alert(element.validationMessage);
                        }
                        else {      
                            $("#entrada_usuario")[0].setCustomValidity("");
                        };
                    },
                    error: function (resultado) { ProcessError(resultado) }
                }
            );

});

<label for="usuario">Usuário:</label>
<input type="text" name="usuario" id="entrada_usuario"  placeholder="Digite o nome de usuário" required />     

validausuario.php page

$usuario = $_POST['usuario'];
$validar = $pdo->prepare("SELECT * FROM usuario WHERE login='$usuario'");
$validar -> execute();
$result = $validar->rowCount();
echo json_encode($resultado);       

1 answer

0

To trigger the error you must perform form Ubmit. It is not possible to trigger the validation only in one element. You can know if it’s valid, like you asked with the .checkValidity() but this does not show the message, only with the form Submit.

Besides, your code sounds good, and .setCustomValidity() works well.

Example:

var input = document.querySelector('input');
console.log(input);
input.setCustomValidity('Usuário já existe!');
console.log(input.checkValidity())
console.log(input.validity)
<form action="">
	<input type="text">
	<button type="submit">Enviar</button>
</form>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.