简体   繁体   中英

JQuery Validation - custom rule

I have a simple form

<form role="form" id="my_form" class="form-horizontal">
    <label class="radio">
        <input type="radio" name="reason[]" id="reasonOne" value="1"> Something
    </label>
    <label class="radio">
        <input type="radio" name="reason[]" id="reasonTwo" value="2"> Something else
    </label>
    <label class="radio">
        <input type="radio" name="reason[]" id="reasonThree" value="Other"> Other 
    </label>
    <input type="text" name="reason[]" placeholder="Please specify" id="other" class="form-control">
</form>

The bottom radio controls a text input. Initially this is hidden, and I do

$('input:radio[name="reason[]"]').change(
    function(){
        if ($(this).is(':checked') && $(this).val() == 'Other') {
            $('#other').css("display", 'block');
        } else {
            $('#other').css("display", 'none');
        }
    }
);

Defining rules for radio buttons is straight forward, I just need to make sure one is selected. I am having a few issues with a custom rule. Essentially, if reasonThree is selected, I need to make sure they enter something into the text input which is at this point displayed. At this moment, I am trying something like the following.

jQuery.validator.addMethod('customrule', function() {
    if($("input[id='reasonFive']:checked")) {
        if(('#other').val().length == 0) {
            return false;
        } else {
            return true;
        }
    }
    return false;
}, 'Please input a reason' );

var validator = $("#my_form").validate({
    rules: {
        'reason[]': {
            required: true,
            customRule: true
        }
    },
    messages: {
        'reason[]': {
            required: jQuery.validator.format("Please select an option")
        }
    }
});

If they select the last radio button, how can I make sure they enter something into the text area?

Thanks

There is no element with id [id='reasonFive'] . Try to change your custom method like this:-

$.validator.addMethod("customRule",function(value,element){
   if($('#reasonThree').is(':checked')){
     return $('#other').val().trim().length>0;
  }else{
    return true;
  }
},"Please input a reason");

Demo

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