setCustomValidity does not work with Ajax

2

In a field change event I try to validate a user name through an Ajax call. Apparently html5's setCustomValidity does not work with jQuery. I ask for help for those who handle 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 />     

page validausuario.php

$usuario = $_POST['usuario'];
$validar = $pdo->prepare("SELECT * FROM usuario WHERE login='$usuario'");
$validar -> execute();
$result = $validar->rowCount();
echo json_encode($resultado);       
    
asked by anonymous 13.07.2017 / 00:00

1 answer

0

To trigger the error you have to submit the form. It is not possible to trigger validation on only one element. You can tell if it is valid, as you had in the question with .checkValidity() but this does not show the message, only with the form submit.

Otherwise your code looks good and .setCustomValidity() works fine.

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>
    
13.07.2017 / 00:10