我正在使用validate.js而我正在尝试显示特定错误,而只是一条错误消息。但我只是无法显示错误。它们通过控制台在是否存在错误时工作正常,但是当我们遇到特定错误时它不起作用。这是我到目前为止的代码
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="validate.js"></script>
</head>
<body>
<form name="form1" action="#" method="post">
<input type="text" name="name" placeholder="Name">
<br>
<input type="text" name="email" placeholder="Email">
<br>
<input type="password" name="password" placeholder="Password">
<br>
<input type="submit" value="Submit">
</form>
<script>
var validator = new FormValidator('form1', [{
name: 'name',
display: 'required',
rules: 'required'
}, {
name: 'email',
rules: 'valid_email'
}, {
name: 'password',
rules: 'required'
}], function (errors, event) {
if (errors.length > 0) {
var errorString = '';
for (var i = 0, errorLength = errors.length; i < errorLength; i++) {
errorString += errors[i].message + '<br />';
}
el.innerHTML = errorString;
}
});
</script>
</body>
</html>
有什么想法吗?
答案 0 :(得分:0)
我在这做了两件事。首先,插件需要在页面加载后附加到表单。这是通过将代码包装在以下内容中完成的:
window.onload = function(){
// existing code goes here
}
我还添加了一个id为“errors”的div,然后用以下内容填充:
document.getElementById("errors").innerHTML = errorString;
我还将验证规则分离为单独的变量(可选)。我已经附上完整的代码供您审核。
由于
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="validate.min.js"></script>
</head>
<body>
<div id="errors"></div>
<form name="myform" action="#" method="post">
<input type="text" name="name" placeholder="Name">
<br>
<input type="text" name="email" placeholder="Email">
<br>
<input type="password" name="password" placeholder="Password">
<br>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
var rules = [
{
name: 'name',
display: 'required',
rules: 'required'
},
{
name: 'email',
rules: 'valid_email'
},
{
name: 'password',
rules: 'required'
}
];
var validator = new FormValidator('myform', rules, function (errors, event) {
if (errors.length > 0) {
var errorString = '';
for (var i = 0, errorLength = errors.length; i < errorLength; i++) {
errorString += errors[i].message + '<br />';
}
document.getElementById("errors").innerHTML = errorString;
}
});
}
</script>
</body>
</html>