我正在使用jquery验证来验证输入
$("#myForm").validate({
rules : {
"name" : {
required : true,
minlength : 10,
maxlength : 50,
alphanumeric: true
}
},
messages : {
"name" : {
required : "Name is required!",
minlength : "Enter number of characters between 10 and 50."
}
},
success: function(label,element) {
$("#errorMsgDiv").html("");
},
submitHandler : function(form) {
form.submit();
},
errorPlacement: function(error, element) {
$("#errorMsgDiv").html("");
error.appendTo('#errorMsgDiv');
}
});
jsp页面上的文本输入是
<form:input path="name" class="form-control" autocomplete="off" placeholder="Enter Name" id="existingValue" required="required"/>
<div class="col-md-6 col-sm-6" id="errorMsgDiv">
现在,仅在更改文本输入的焦点之后,才会发生验证/验证消息。 如何在输入第一个字符且不等待焦点更改的情况下立即运行验证?
答案 0 :(得分:0)
As I said in my comment to the answer of Apple Orange, his/her solution shouldn't be used since you would submit the validated form too early in edge cases.
If you want to go the focus route, this would do the thing for you. With each keyup
event, the submit button will be focused, then the input you were typing in will be refocused.
$(document).ready(function () {
$(".name, .email").keyup(function(e){
$('#sbt').focus();
$(this).focus();
});
$("#form").validate({
rules: {
"name": {
required: true,
minlength: 5
},
"email": {
required: true,
email: true
}
},
messages: {
"name": {
required: "Please, enter a name"
},
"email": {
required: "Please, enter an email",
email: "Email is invalid"
}
},
submitHandler: function (form) { // for demo
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<form id="form" method="post" action="#">
<label for="name">Name</label>
<input type="text" name="name" class="name" />
<label for="email">Email</label>
<input type="email" name="email" class="email" />
<button type="submit" id="sbt">Submit</button>
</form>