输入文件验证

时间:2014-03-10 07:36:00

标签: javascript jquery validation

我正在使用jquery验证表单。一切正常,但没有文件上传。这里有一个文件上传按钮,只接受我使用Jquery的图像,如下所示

$(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

和我的文件选择器如下,

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

但这不是验证。请帮帮我。

2 个答案:

答案 0 :(得分:0)

确保您的表单如下所示:

<form action="#" method="post" " enctype="multipart/form-data" class="" onsubmit="return Checkfiles(this);">
// ...
  <input type="file" name="file" id="file">
</form>

Jquery:

  function Checkfiles(f){
      f = f.elements;
      if(/.*\.(jpg)$/.test(f['file'].value.toLowerCase()))
        return true;
      alert('Please Upload Jpg Files Only.');
       f['file'].focus();
       return false;
};

答案 1 :(得分:0)

jQuery Validate实际上通过additional-methods.js使用accept规则直接支持此功能。

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

photo:{
    accept:'image/*'
}

这将允许所有图像mimetypes。