jquery validation change field validation on the fly
i am using jquery validation and i have the code above
<script language="javascript">
$(document).ready(function() {
var validator=$("form#myForm")
.validate({
开发者_开发技巧 submitHandler: function(form){
alert("Submited");
},
invalidHandler: function(form, validator) {
var errors = validator.numberOfInvalids();
if (errors) {
console.log(validator.invalidElements());
}
},
rules: {
field1: { required: true }
}
});
})
function changeValidation()
{
var validationType=$("#nextFieldValidation").val();
console.log("selected validation type is "+validationType);
switch(validationType)
{
case "integer":
console.log("set INTEGER validation");
$("#nextField").rules("remove");
$("#nextField").rules("add", {
digits: true
});
break;
case "float":
console.log("set FLOAT validation");
$("#nextField").rules("remove");
$("#nextField").rules("add", {
number: true
});
break;
default:
console.log("REMOVE validation");
$("#nextField").rules("remove");
break;
}
}
</script>
<form id="myForm" name="form" action="action.php">
<div><input type="text" name="field1" id="field1" /></div>
<div>
<select name="nextFieldValidation" id="nextFieldValidation" onclick="changeValidation();">
<option value="">Select next filed validation</option>
<option value="integer">Integer</option>
<option value="float">Float</option>
</select>
</div>
<div><input type="text" name="nextField" id="nextField" /></div>
<div><input type="submit" /></div>
</form>
The nextField validation is controlled by a select box. User decide if nextField is integer or float.
The code is working fine but i need to add something to make increase accessibility for the user.
So here is the problem.
Scenario:
user fills field1 select integer validation and fills with 12.8 and click submit He gets error "Please enter only digits." which is correct
After that change the validation to float.
Here is the problem. the error "Please enter only digits." is still there and its kind of confusing.You must submit the form to proceed but why anyone click submit when get an error.
So is there any way when changing the select box value somehow revalidate the form or revalidate only the specific nextFiled in order to remove the error
Thanks
I suggest that you change the call to "changeValidation()" to occur onchange, instead of onclick. onclick is likely firing when you click the control to give it focus, not when you select a different option. As a result, at the time that it runs the validation, it is still set as an integer.
So, try changing:
<select name="nextFieldValidation" id="nextFieldValidation" onclick="changeValidation();">
To:
<select name="nextFieldValidation" id="nextFieldValidation" onchange="changeValidation();">
精彩评论