The jQuery Validation plugin provides nice functionality for client-side validation and is easy to customize. Here are some custom validators I wrote for the .NET FileUpload control (Framework 4.5). These functions validate that a file has been selected and has the desired extension and size.
- (function (UTIL, $) {
- "use strict";
- UTIL.image_file_extensions = ['.png', '.jpg', '.jpeg', '.gif', '.bmp'];
- UTIL.getFileExtension = function (filename) {
- var idx = filename.lastIndexOf('.');
- return filename.substring(idx, filename.length);
- };
- UTIL.validateFileExtensions = function (element, valid_extensions) {
- var files = element.files,
- i = 0,
- max = files.length,
- ext = '',
- is_valid = true;
- while (i < max && is_valid === true) {
- ext = UTIL.getFileExtension(files[i].name);
- is_valid = ($.inArray(ext, valid_extensions) !== -1);
- i += 1;
- }
- return is_valid;
- };
- if ($.validator) {
- $.validator.addMethod("fileupload_required", function (value, element) {
- var is_valid = element.files.length > 0;
- return is_valid;
- }, "You must select a file for upload");
- $.validator.addMethod("fileupload_image_extensions", function (value, element) {
- var is_valid = UTIL.validateFileExtensions(element, UTIL.image_file_extensions);
- return is_valid;
- }, "You must select a valid image (.png, .jpg, .gif, .bmp) file for upload");
- $.validator.addMethod("fileupload_size", function (value, element) {
- var files = element.files,
- i = 0,
- max = files.length,
- ext = '',
- is_valid = true;
- while (i < max && is_valid === true) {
- is_valid = (files[i].size <= 4194304);
- i += 1;
- }
- return is_valid;
- }, "You must select a file that is smaller than 4 MB");
- }
- }(Utilities, jQuery));
Once the custom validators are defined, they can be applied to any FileUpload control by defining the rules for that control:
- $('Form').validate({
- rules.fileUploadControlUniqueId = {
- fileupload_required: true,
- fileupload_image_extensions: true,
- fileupload_size: true
- }
- });
Note that the validations are applied in the order that they are added to the rules object. In the example above, the FileUpload control would be validated first for a required file, then for the file extension, then for file size.
No comments:
Post a Comment