我一直在尝试使用jQuery 验证插件来验证移动表单,但没有取得多大成功。
好像我访问的第一页有一个表单验证没问题。后续页面不会验证,除非它们具有与第一页上存在相同的字段以进行验证。
例如,我访问的第一个页面是登录页面。它有 2 个字段,电子邮件地址和密码。
代码是:
<body>
<div id="Login" data-role="page">
<script type="text/javascript">
$(document).on('pageinit pageshow', 'div:jqmData(role="page"), div:jqmData(role="dialog")', function(){
if($("form.validate").length > 0){
$("form.validate").validate({
rules: {
email_address: {
required: true,
email: true
},
password: "required"
}
});
}
});
</script>
<form name="login" method="post" class="validate">
<label class="inputLabel" for="login-email-address">Email Address:</label>
<input type="email" name="email_address" size="18" id="login-email-address" />
<label class="inputLabel" for="login-password">Password:</label>
<input type="password" name="password" size="18" id="login-password" />
<input type="submit" value="Log In" data-icon="lock" data-mini="true" alt="Log In" title=" Log In " />
</form>
</div>
</body>
这在我点击提交按钮时验证。如果我从登录页面点击按钮进入创建帐户页面,该页面有 4 个字段 - 名字、姓氏、电子邮件地址和密码,仅验证电子邮件地址和密码。
创建帐户页面如下所示:
<body>
<div id="CreateAccount" data-role="page">
<script type="text/javascript">
$(document).on('pageinit pageshow', 'div:jqmData(role="page"), div:jqmData(role="dialog")', function(){
if($("form.validate").length > 0){
$("form.validate").validate({
rules: {
firstname: {
required: true,
minlength: 2
},
lastname: {
required: true,
minlength: 2
},
email_address: {
required: true,
email: true
},
password: "required"
}
});
}
});
</script>
<form name="create_account" method="post" class="validate">
<label class="inputLabel" for="create-account-firstname">First Name:</label>
<input type="text" name="firstname" size = "41" maxlength= "96" id="create-account-firstname" />
<label class="inputLabel" for="create-account-lastname">Last Name:</label>
<input type="text" name="lastname" size = "41" maxlength= "96" id="create-account-lastname" />
<label class="inputLabel" for="create-account-email-address">Email Address:</label>
<input type="email" name="email_address" size="18" id="create-account-email-address" />
<label class="inputLabel" for="create-account-password">Password:</label>
<input type="password" name="password" size="18" id="create-account-password" />
<input type="submit" value="Submit" data-icon="lock" data-mini="true" alt="Submit" title=" Submit " />
</form>
</div>
</body>
如果我点击此页面上的提交按钮,则只会验证电子邮件地址和密码。我假设这是因为它仍在从登录页面而不是创建帐户页面运行验证规则?如果我点击浏览器刷新,那么提交按钮的所有 4 个字段都会被验证。
如何正确验证表单?