Extjs adding file extension validation client side

One of the great things about extjs and all third party javascript libraries is the ease at which you can add the html file upload control to your page, and make it look professional. One of the things that almost every file upload application that I seen in use is a client side validation that is based on file extension, think about it would you like any file type making it to your server, including executables? The following code will add the file extension check to the upload on the client side. All you have to do is use the xtype ‘restfileupload’, and pass the extensions in an array without the period before the letters. Have Fun!

/***********************************************
Adds extension validation at the client side
for the extjs File Upload field. You must
set the extension in an array of strings.
 **********************************************/
Ext.define('Ext.ux.restrictiveFileUpload', {
	extend  : 'Ext.form.field.File',
	alias   : 'widget.restfileupload',
	// Array of acceptable file extensions
	// overridden when decalred with a string
	// of extensions minus the period.
	accept      	: [],
	listeners   	: {
    	validitychange : function(me) {
        	// This gets the part of the file name after the last period
        	var indexofPeriod = me.getValue().lastIndexOf("."),
            	uploadedExtension = me.getValue().substr(indexofPeriod + 1, me.getValue().length - indexofPeriod);
 
        	// See if the extension is in the 
                //array of acceptable file extensions
        	if (!Ext.Array.contains(this.accept, uploadedExtension)){
            	// Add the tooltip below to 
                // the red exclamation point on the form field
      	      me.setActiveError('Please upload files with an extension of :  ' + this.accept.join() + ' only!');
           	// Let the user know why the field is red and blank!
            	Ext.MessageBox.show({
                	title   : 'File Type Error',
                	msg 	: 'Please upload files with an extension of :  ' + this.accept.join() + ' only!',
                	buttons : Ext.Msg.OK,
                	icon	: Ext.Msg.ERROR
            	});
            	// Set the raw value to null so that the extjs form submit
            	// isValid() method will stop submission.
            	me.setRawValue(null);
        	}
    	}
	}
});

Leave a Reply