输入文件验证 [英] Input file validation

查看:94
本文介绍了输入文件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery验证表单.一切正常,但无法上传文件.这里有一个文件上传按钮,该按钮仅接受我按照以下方式使用Jquery的图像,

I am validating form using jquery . All is working fine but not file uploading. here there is a file upload button which accept only images for that I use Jquery as follow,

$(document).ready(function(){


    $('#create_teacher').validate({
    rules: {
        teacherId: {

        required: true
      },

        teacherName: {
        minlength: 6,
        required: true
      },

        education: {
            required: true,
            minlength: 6
        },

        experience: {
            required: true,
            minlength: 6

        },

        prevdetails:{
            required: true,
            minlength: 6

        },
        email: {
        required: true,
        email: true
      },


        highlight: function(element) {
            $(element).closest('.control-group').removeClass('success').addClass('error');
        },
        success: function(element) {
            element
            .text('OK!').addClass('valid')
            .closest('.control-group').removeClass('error').addClass('success');
        }
    }
  });


$('#create_teacher input[type="submit"]').click(function(e){
        e.preventDefault();
        var form = $('#create_teacher');
        var file = $('input[type="file"]', form).val();
        var exts = ['jpg','jpeg','gif','png'];
        var msg = $('.msg', form);
        msg.hide();

        // first check if file field has any value
        if ( file ) {
            // split file name at dot
            var get_ext = file.split('.');
            // reverse name to check extension
            get_ext = get_ext.reverse();

            // check file type is valid as given in 'exts' array
            if ( $.inArray ( get_ext[0].toLowerCase(), exts ) > -1 ){
                msg.show().html( '<strong style="color:#090">Allowed extension!</strong>' );
            } else {
                msg.show().html( '<strong style="color:#f00">Invalid file!</strong>' );
            }
        }else{
            msg.show().html( '<strong style="color:#f00">Select file!</strong>' );
        }
    });

}); // end document.ready

和我的文件选择器如下,

and my file picker as follow,

<input type="file"  id="photo" name="photo" />

,但这没有验证.请帮助我.

but this is not validating . Please help me.

推荐答案

jQuery Validate通过接受的Additional-methods.js"rel =" nofollow> additional-methods.js a>规则.

jQuery Validate actually supports this directly, via additional-methods.js, using the accept rule.

您要做的是在页面中包含该.js文件,然后将规则添加到规则对象中,如下所示:

What you would do is include that .js file in your page, and add a rule to your rules object that looks like this:

photo:{
    accept:'image/*'
}

将允许所有图像模仿类型.

Which will allow all image mimetypes.

这篇关于输入文件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆