我有一些JQuery表单验证,其中我检查用户名的长度对于数据库来说不长,但它似乎返回真正的eveytime.
我错过了什么吗?
HTML
<form name="contact" method"post" action="">
<fieldset>
<label for="username" id="username_label" class="form_label">Username</label>
<input type="text" name="username" id="username" size="30" value="" class="text-input" />
<label class="error" for="username" id="username_error">This field is required. </label>
<label class="error" for="username" id="username_length">Your Username should be less than 30 characters.</label>
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</fieldset>
</form>
Run Code Online (Sandbox Code Playgroud)
JavaScript的
$(function() {
$('.error').hide();
$(".button").click(function() {
// validate and process form here
$('.error').hide();
var username_length = $("input#username").val().length;
if (username_length < 30) {
$("label#username_length").show();
$("input#username").focus();
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用JQuery Validator插件来执行此操作;
只需要改变你的html这样的东西;
<label for="username">User Name:</label>
<input type="text" name="username" id="username" value="..." />
Run Code Online (Sandbox Code Playgroud)
使用这种方法你不需要用不同的id(username_error,username_length)定义这个多个标签标签来处理每一个约束消息,并且不需要担心隐藏这些标签,jquery插件会为你处理这个并放入lable rotule中的相应消息,带有'username'.并随意自定义此消息.
你的js会是这样的;
$("form[name=contact]").validate({
//...
rules: {
username: {
required: true,
maxlength: 30
}
//...
});
Run Code Online (Sandbox Code Playgroud)
您的代码将更加干净,有关详细信息,请参阅API文档,http: //docs.jquery.com/Plugins/Validation
| 归档时间: |
|
| 查看次数: |
27073 次 |
| 最近记录: |