Вопрос

I have set custom validation for my form validation, but if has a invalid field, I need put values and valid it 2 times, only in second time, it will valid next field, what is problem?

View in jsfiddle

My form:

<form>
    <label>Login:</label>
    <input type="text" name="login" id="login" required/><br/>
    <label>Password:</label>
    <input type="password" name="pass" id="pass" required/><br/>
    <label>Password Confirm:</label>
    <input type="password" name="pass_conf" id="pass_conf" required/><br/>

    <input type="submit"/>
</form>

My Javascript:

// This code is loaded in $(document).ready();
$("input").on("invalid", function (e) {
    console.log("Invalidd");
    if (!e.target.validity.valid) {
        var msg = "";
        if (e.target.validity.valueMissing) {
            msg = "Esse campo é obrigatorio.";
        }
        if (e.target.validity.patternMismatch) {
            msg = "Formato incorreto.";
        }

        e.target.setCustomValidity(msg);
    }
});
Это было полезно?

Решение

You might want to add the change event to your inputs as well as shown in the example at mdn.

var inputs = $("form").find("input:not([type='submit'])"),
    validate = function (input) {
        var msg = "";

        if (!input.validity.valid) {
            if (input.validity.valueMissing) {
                msg = "Esse campo é obrigatorio.";
            }
            if (e.target.validity.patternMismatch) {
                msg = "Formato incorreto.";
            }
        }
        input.setCustomValidity(msg);
    };

inputs.on("change invalid", function (e) {
    validate(e.target);
});

demo

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top