I tried this custom validator to validate file extension of selected file.
I use valdr-validation-plugin with AngularJS and have written this custom validation to validate the extension of the file which is to be uploaded.
Generally value
parameter contains the details of the data which is to be validated, but in case of file upload its not working.
app.factory('fileValidator', function () {
return {
name: 'fileExtension',
validate: function (value, arguments)
{
if(value=== undefined) { return false; }
else
{
var fileName = value.name,
extension = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase();
if( extension == "jpg" || extension == "jpeg" || extension == "png" || extension == "bmp" ){ return true; }
else { return false; }
}
}
};
});
In above code, I try to get the extension of file using value
parameter but it showing error that value is undefined.
I call this custom validation from the below code. Register that validator to the app config and then used it to validate bannerImage.
app.config(function(valdrProvider) {
valdrProvider.addValidator('fileValidator');
valdrProvider.addConstraints({
"Banner":
{
"bannerName":
{
"size":
{
"min": 2,
"max": 512,
"message": "Banner name must between 2 and 512 characters"
},
"required" :
{
"message" : "This field is required"
}
},
"bannerLink":
{
"size":
{
"min": 2,
"max": 1024,
"message": "Banner link must between 2 and 1024 characters"
},
"required" :
{
"message" : "This field is required"
}
},
"bannerImage":
{
"fileExtension":
{
"allowedExtensions" : ['jpg','jpeg', 'png','bmp'],
"message" : "Allowed file types are JPG, JPEG, PNG, BMP"
},
"required":
{
"required" : "This field is required"
}
}
}
});
});
Its not working and shows lot of errors. How can I solve this issue?