changing validation of input value based on list-box value
I am using jQuery validation plugin ( http://bassistance.de/jquery-plugins/jquery-plugin-validation/ )
I have following structure:
<select name="s1" id="s1">
<option value="url">url</option>
<option value="normal">normal</option>
</select>
<input name="s1_value" id="s1_value" type="text" />
Now, I need validation rule (using jQuery validation plugin) as
If I select 'url' as value in list box, then input field should only cont开发者_开发百科ain valid URL
If I select 'normal' as value in list box, then input field can contain any text
For any selection, value for input field should not be empty
How to do this?
The validation plugin allows rules to be specified in each element's class. You can start with the required
and url
rules:
<input name="s1_value" id="s1_value" type="text" class="required url" />
From there, you can remove the url
class if the list box value becomes normal
:
$("#s1").change(function() {
if ($(this).val() == "url") {
$("#s1_value").addClass("url");
} else {
$("#s1_value").removeClass("url");
}
});
That way, the validation plugin won't validate the field against the url
rule, since it does not expose that rule in its class.
You can test this solution here.
Well I think the simpliest solution could be just using the http://docs.jquery.com/Plugins/Validation/rules#.22add.22rules rules("add",rules) function to add and rules("remove",rules) to remove rules depending on select value of that select.
$("select").change(function(){
if(this.value == "url") {
$("input").rules("add",{
url: true
})
}
if(this.value == "normal") {
$("input").rules("remove", "url")
}
})
You could connect a change
event to the select input:
jQuery("#s1").change(function(){
var val = jQuery(this).val();
...
});
Then within that function, use the add
and remove
functions from the validation plugin to adjust your rules as necessary.
精彩评论