Search code examples
jqueryvalidationfile-type

jQuery File Type Validation Based on Radio Buttons


I'm trying to validate file type base on radio button selection. If the user click on "Display Ad". He/She can only upload image files and if the user selects "Video", he/she can only upload video files. Furthermore, they can only upload file on certain size only which I might be able to do it later. The main problem for me now is I can't validate image file and video file. Here's my jsfiddle: http://jsfiddle.net/MZu3g/

Below is my sample code for the javascript.

$('.form_validation_reg3').validate({
    onkeyup: false,
    errorClass: 'error',
    validClass: 'valid',
    highlight: function (element) {
        $(element).closest('div').addClass("f_error");
    },
    unhighlight: function (element) {
        $(element).closest('div').removeClass("f_error");
    },
    errorPlacement: function (error, element) {
        $(element).closest('div').append(error);
    },
    rules: {
        'gender[]': {
            required: '#adtarget_check:checked',
            minlength: 1
        },
            'target_age[]': {
            required: '#adtarget_check:checked',
            minlength: 1
        },
            'target_time[]': {
            required: '#adtarget_check:checked',
            minlength: 1
        },
            'target_device[]': {
            required: '#adtarget_check:checked',
            minlength: 1
        },
            'target_location[]': {
            required: '#adtarget_check:checked',
            minlength: 1
        },
            'target_network[]': {
            required: '#adtarget_check:checked',
            minlength: 1
        },
        notebook: {
            required: true,
            minlength: 1,
            accept: "jpg|jpeg|png|ico|bmp"
        },
        mobile: {
            required: false,
            minlength: 1,
            accept: "jpg|jpeg|png|ico|bmp"
        },
    },
    invalidHandler: function (form, validator) {
        $.sticky("There are some errors or no Ads image were selected. Please correct them and submit again.", {
            autoclose: 8000,
            position: "top-right",
            type: "st-error"
        });
    }
})

Solution

  • Found the solution... by adding these..

    var radio_value = null;
    $("input[name='tabnote_radio']").change(function() {
        radio_value = this.value;
        if ( radio_value == "image") {
            $('#notebook').rules('add', {
                extension: "jpg|jpeg|png|gif"
            });
        } else if( radio_value == "video") {
            $('#notebook').rules('add', {
                extension: "flv|mov|mp4|wmv|ogv"
            });
        };
    });
    

    This can be useful too: http://snippets.aktagon.com/snippets/490-how-to-add-and-remove-validation-rules-jquery-validate-plugin-