javascript - jQuery validator not working for file input type -
i trying implemenet validation file input type using jquery validator plugin. file input type should accept images .jpeg, .jpg & .png extension & file size should not greater 1mb. validation other input fields work without issues. required validation works file input type.
what issue?
javascript
jquery.validator.addmethod('filesize', function(value, element, param) { return this.optional(element) || (element.files[0].size <= param) }); $('#form').validate({ rules: { firstname: { minlength: 6, required: true }, lastname: { minlength: 6, required: true }, file: { required: true, accept: "png|jpeg|jpg", filesize: 1048576 } }, messages: { file: "file must jpeg or png, less 1mb" }, highlight: function(element) { $(element).closest('.form-group').addclass('has-error'); }, unhighlight: function(element) { $(element).closest('.form-group').removeclass('has-error'); }, errorelement: 'span', errorclass: 'help-block', errorplacement: function(error, element) { if(element.parent('.input-group').length) { error.insertafter(element.parent()); } else { error.insertafter(element); } } });
html
<form id="form"> <div class="form-group"> <label class="control-label" for="firstname">first:</label> <div class="input-group"> <input class="form-control" name="firstname" type="text" /> </div> </div> <div class="form-group"> <label class="control-label" for="lastname">last:</label> <div class="input-group"> <input class="form-control" name="lastname" type="text" /> </div> </div> <div class="form-group"> <label class="control-label" for="file">image:</label> <div class="input-group"> <input id="file" name="file" type="file" /> </div> </div> <button type="submit" class="btn btn-primary">submit</button> </form>
...should accept images .jpeg, .jpg & .png extension
the
accept
rule mime types. theextension
rule file extensions. looks should usingextension
rule instead ofaccept
. need include theadditional-methods.js
file in order use these rules.in order have access file's size property, need set
enctype="multipart/form-data"
attribute on<form>
tag.
working demo: http://jsfiddle.net/mv8w3m0c/1/
Comments
Post a Comment