Jquery文件验证器:如何成功调用函数?

时间:2014-06-19 19:47:12

标签: javascript jquery html html5 validation

我正在使用jquery文件验证器插件。 这是链接:
http://adamsanderson.github.io/jQuery-File-Validator/#documentation
我可以在验证之前调用函数 onInvalid 输入 但有人可以告诉我,如果文件是有效输入,我怎么能调用函数?
这是代码..

$( el ).fileValidator({
    onValidation: function(files){ /* Called once before validating files */ },
    onInvalid:    function(validationType, file){ /* Called once for each invalid file */ },
    maxSize:      '2m', //optional
    type:         'image' //optional
});

2 个答案:

答案 0 :(得分:1)

好的,需要对插件进行一些更改,因为这些更改会在整个文件中传播,所以我不会详细介绍,但这是您需要的版本:

/**

Uploading files, only to find that they are too large, or the wrong type is frustrating.
The `fileValidator` plugin lets you warn users before they start uploading 
enormous files.

Usage
-----

Simply select the file inputs you wish to validate, and pass in a callbacks to handle invalid files.

    $( el ).fileValidator({
      onValidation: function(files){ ... },
      onInvalid:    function(validationType, file){ ... },
      maxSize:      '2m', //optional
      type:         'image' //optional
    });



*/
(function($){

  validFile = true;

  $.fileValidator = function(options){
    var validations = [];
    var onInvalid = options.onInvalid;
    var onValid = options.onValid;


    for (var key in $.fileValidator.validations){
      if (!options[key]){ continue; }
      validations.push( $.fileValidator.validations[key](options[key], onInvalid, onValid));
    }


    return function(file){
      for(var i=0, len = validations.length; i < len; i++){
        validations[i].call(this, file);
      }
      if(validFile){onValid.call();}
    };
  };

  $.fileValidator.validations = {
    maxSize: function(maxSize, invalid, valid){
      if( typeof maxSize == 'string' ){ 
        maxSize = $.fileValidator.sizeToBytes(maxSize);
      }

      return function(file){
        if (file.size > maxSize){ invalid.call(this,'maxSize',file); validFile = false; }
      };
    },

    type: function(contentType, invalid, valid){
      var isValid;
      if( typeof contentType == 'function' ){ 
        isValid = contentType; 
      } else if (contentType.constructor === RegExp ) { 
        isValid = function(type){ return type.match(contentType); }; 
      } else { 
        isValid = function(type){ return ~type.indexOf(contentType); }; 
      }

      return function(file){
        if (!isValid(file.type)) { invalid.call(this,'type', file); validFile = false; }
      };
    }
  };

  $.fn.fileValidator = function(userOptions) {
        var options = $.extend({
          // Validations
          maxSize: null,
          type: null,

          // Callbacks
          onValidation: $.fileValidator.doNothing,
          onInvalid: $.fileValidator.doNothing,
      onValid: $.fileValidator.doNothing
        }, userOptions);

        return this.each(function() {
            var el = $(this);
            var validator = $.fileValidator( $.extend({}, options, el.data()) );

          el.bind('change', function(event){
            var files = this.files || [];
            options.onValidation.call(this, files);
            for(var i=0, len=files.length; i < len; i++){
              validator.call(this, files[i]);
            }
          });
        });     
    };

  $.fileValidator.doNothing   = function doNothing(){};
  $.fileValidator.sizeToBytes = function sizeToBytes(size){
    var scale = 1;

    if (~ size.indexOf('k')){ 
      scale = 1024; 
    } else if (~ size.indexOf('m')){ 
      scale = 1024 * 1024; 
    } else if (~ size.indexOf('g')){ 
      scale = 1024 * 1024 * 1024; 
    }
    return parseInt(size,10) * scale;
  };
})( jQuery );

像这样使用:

$(function(){  
    $('input').fileValidator({
        onValidation :  function(){ validFile=true; },
        onInvalid:      function(type, file){ alert('Error: '+type); },
        onValid :       function(){ alert('Yay!'); },
        type:        'image',
        maxSize:      '1m'
    });
});

JS Fiddle Demo

修改

validFile变量从一开始就为真,如果遇到错误,则变为false。

答案 1 :(得分:0)

如果您只是通过扩展来验证它们,请创建您自己的简单js方法。例如:

<!-- File input in form -->
<input id="myId" class="button" name="myFile" type="file" onchange="getName()" >

<script>
    function getName() {
        var filename = document.getElementById("myId").value;
    alert(filename.split('.').pop());
    }
</script>