使用Jquery进行表单验证

cha*_*111 1 html forms validation jquery

我正在使用jQuery来验证我的表单.我想看看用户名是否只是一个单词.我在Jquery http://jqueryvalidation.org/category/selectors/中看到了选择器,但在我的情况下不知道如何使用它.

<form id="register" name="register" action="/codejudge/contest.php" method="post" >
<label for ="Username"> Username </label><br>
<input type="text" class="register-control" id="Username" name="Username"  placeholder="Enter Username"> <br><br>
<label for ="Password"> Password </label><br>
<input type="password" class="register-control" id="password" name="password" placeholder="Enter Password" ><br><br>
<label for ="Confirm-Password"> Confirm Password </label><br>
<input type="password" class="register-control" id="Confirm_Password" name="Confirm_Password" placeholder="Confirm Password" ><br><br>
<label for="email" > Email </label><br>
<input type ="email" class="register-control" id="email" name="email" placeholder="Enter Valid Email"><br><br>
<button type="submit" >Submit</button>

</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#register").validate({
errorElement: 'div',
rules:{
    "Username":{
    required: true,     
    minlength:5
    },
"password":{
required:true,
minlength:5
},
"Confirm_Password":{
required:true,
equalTo: "#password"
},
"email":{
required:true,  
}
},
messages: {
    Username:{
                 required: "Please provide a username",
                minlength: "Your password must be at least 5 characters long"
    },
     password: {
                required: "Please provide a password",
                minlength: "Your password must be at least 5 characters long"
                },
     Confirm_Password: {
                required: "Please provide a confirm password",
                equalTo: "Please enter the same password as above"
                }
    },
    email:{
                required: "Please provide a valid email",
    } 
  });  
 });
 </script>
Run Code Online (Sandbox Code Playgroud)

小智 5

  1. 添加这种验证器(函数):
jQuery.validator.addMethod('word_check', function (value, element) { 
  var word = "ausername";
  var space_check = word.split(" ")[1];
  //if space check is undefined you have a single word!
});
Run Code Online (Sandbox Code Playgroud)

现在在您的规则代码中:

rules:{
    "Username":{
    required: true,     
    minlength:5,
    word_check : true
    },
Run Code Online (Sandbox Code Playgroud)