简体   繁体   中英

Dynamic form field validation using jquery AND Rules

This question is an extension of my SO question:

jQuery to disable/enable textarea depending on which radio button is selected inside of loop

I'm using the jQuery bassistance validation plugin ( http://bassistance.de/jquery-plugins/jquery-plugin-validation/ ).

The validation rule I'm trying to create is if a radio button equals 'yes', then make the textarea a required field. My ID's and form field names for the radio and textarea boxes are dynamic but begin with the same word so I can use name^='travel'

HTML UPDATED

<div class="controls">
    <label class="radio inline">
        <input type="radio" name="travel_1" data-travelNumber="1" id="travel_yes_1" value="Yes" tabindex="25" >
        Yes </label>
    <label class="radio inline">
        <input name="travel_1" type="radio" data-travelNumber="1" id="travel_no_1" value="No" tabindex="26" checked >
        No </label>
</div>
<div class="controls" id="Answer_travel_yes_1">
    <textarea name="travelDetails_1" id="travelDetails_1" ></textarea>
</div>

<div class="controls">
    <label class="radio inline">
        <input type="radio" name="travel_2" data-travelNumber="2" id="travel_yes_2" value="Yes" tabindex="25" >
        Yes </label>
    <label class="radio inline">
        <input name="travel_2" type="radio" data-travelNumber="2" id="travel_no_2" value="No" tabindex="26" checked >
        No </label>
</div>
<div class="controls" id="Answer_travel_yes_2">
    <textarea name="travelDetails_2" id="travelDetails_2"></textarea>
</div>


<div class="controls">
    <label class="radio inline">
        <input type="radio" name="travel_3" data-travelNumber="3" id="travel_yes_3" value="Yes" tabindex="25" >
        Yes </label>
    <label class="radio inline">
        <input name="travel_3" type="radio" data-travelNumber="3" id="travel_no_3" value="No" tabindex="26" checked >
        No </label>
</div>
<div class="controls" id="Answer_travel_yes_3">
    <textarea name="travelDetails_3" id="travelDetails_3"></textarea>
</div>

jQuery

//  I use this to hide/show the travelDetails textarea (show on yes, hide on no)
$('input:radio[name^="travel"]:checked').live('click',function(){
    var id = $(this).attr("id").split("_");
    id = id[id.length-1];
    $("#travelDetails_" + id).attr("disabled", !($(this).val() == "Yes"));
    if ( $(this).val() == 'Yes' ) 
        $('#Answer_travel_yes_' + id).slideDown();
    else
        $('#Answer_travel_yes_' + id).slideUp();
});


$("#TravelForm").validate({
        rules:{
            whatgoeshere:{
                    required: function(){
                        if ( $("input:radio[name^=travel]:checked").val() == "Yes" ){
                            //  make travel
                            true
                        }
                        else{
                            console.log('false');
                            true
                        }
          },
                    minlength: 10   // needs to have at least 10 characters entered (if the corresponding radio is Yes
            }
        },
        messages:{
            whatgoeshere:{
                required:"Please enter your travel details",
                minlength:"Please enter at least 10 characters"
            }
        },
        errorClass: "help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
            //  $(element).parents('.control-group').addClass('success');
        }
    });

This is a generic answer which you can apply into your code...


I am fairly certain you cannot use a function inside the rules option. As per documentation , rules: need to be "key/value pairs", unless using the depends property.

rules: {
    mytextarea: {
        minlength: 10,
        required: {
            depends: function(element) {
                return $("#myradio:checked")
            }
        }
    }
},
messages: {
    mytextarea: {
        required: "Please enter your travel details",
        minlength: "Please enter at least 10 characters"
    }
}

mytextarea would be the value of the name attribute of your textarea .

<textarea name="mytextarea"></textarea>

Alternatively...

Apply jQuery .validate() rules dynamically.

First initialize your .validate() plugin with options:

$('form').validate({
    // your options, leave out the rule in question
});

Create a rules array (note the slightly different format when using messages ):

var myrule = {
    required: true,
    minlength: 10,
    messages: {
        required: "Please enter your travel details",
        minlength: "Please enter at least 10 characters"
    }
}

Then within your conditional, target the textarea as required:

if ($(this).val() == 'Yes') {
    $('[name^="travel"]').rules('add', myrule);
} else {
    $('[name^="travel"]').rules('remove', myrule);
}

http://docs.jquery.com/Plugins/Validation/rules#.22add.22rules


BTW, .live() has been deprecated in favor of .on() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM