Live Validation simple File Validation

Taking a breath from this speeding job, lol, it probably makes no sense, but has been crazy here.. anywho!

This is a simple snippet or recipe for using the marvelous Live Validation on a simple file extension verification.

The advantage of this is huge, because you can check the kind of file being sent without your server handling the full download of the file! And the user has a quicker feedback! Win – Win

Validate.Anexo = function(value, options) {
    var extensoes = options.ext.split(" ") || ['png', 'jpg', 'bmp', 'gif', 'jpeg']
    var message = options.failureMessage || "A extensão do arquivo está incorreta, são aceitos: " + extensoes.join (' ');
    if (  validateArquivo(value, extensoes)  )
        Validate.fail(message);
    return true;
}

function validateArquivo(val, extensoes){
	var exp = ".*\.(" + extensoes.join('|')+")$" 
	exp = new RegExp(exp,'i') // ex: /.*.(png|jpg|bmp|gif|jpeg)$/i
	if (val.length > 0) {
		return ( ! exp.test(val) )
	}
	return true;
}

Then you use on the view through the arg -> ‘ext’, that should be a string insensitive, where every extension is separated by space

var file = new LiveValidation('document_atach', {validMessage: " ", onlyOnSubmit: true} )
					.add(Validate.Anexo, { ext : 'xml txt doc' } )
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s