我已经为表单验证设置了自定义验证,但是如果有一个无效字段,我需要输入值并将其有效2次,仅在第二次,它将在下一个字段中有效,有什么问题?
我的表格:
<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>
我的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);
}
});
答案 0 :(得分:1)
您可能希望将更改事件添加到输入中,并在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);
});