In my MVC web application, I have a form with a imageupload component. The imageupload Image-data is validated with help of data-annotation. My server side validation is WORKING, but my client side jQuery function is not being called ... I don't know why- HELP:
1. File-upload in my View:
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
<input type="file" id="FileUploader" name="FileUploader" multiple />
<div id="FileDisplay" name="FileDisplay"></div>
@Html.ValidationMessageFor(model => model.FileUploader, "", new { @class = "text-danger" })
2. In my Model, i have this:
[ValidImageUpload]
public IEnumerable<HttpPostedFileBase> FileUploader { get; set; }
3.ValidImageUpload file:
public sealed class ValidImageUpload : ValidationAttribute, IClientValidatable
{
string[] stringArray = { "gif", "jpg", "png", "jpeg" };
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
IEnumerable<System.Web.HttpPostedFileBase> uploadedFiles = (IEnumerable<System.Web.HttpPostedFileBase>)value;
var firstfile = uploadedFiles.FirstOrDefault();
if (firstfile != null)
{
foreach (var file in uploadedFiles)
{
int pos = Array.IndexOf(stringArray, file.ContentType.Substring(6));
if (pos > -1)
{
if (file.ContentLength > 5242880)
{
return new ValidationResult(String.Format("Billedet: {0} er for stort. (Max. tilladt billede-størrelse xxxxx)", file.FileName));
}
}
else
{
return new ValidationResult(String.Format("Billedt: {0} har et forkert format. Tilladte formater er - GIF, JPG, PNG, JPEG", file.FileName));
}
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule mvr = new ModelClientValidationRule();
mvr.ErrorMessage = "Forkert format";
mvr.ValidationType = "validImageUpload";
return new[] { mvr };
}
}
jQuery
$(document).ready(function () {
jQuery.validator.addMethod('validImageUpload', function (value, element, params) {
var currentDate = new Date();
alert('Working indsi´side');
return false;
}, '');
jQuery.validator.unobtrusive.adapters.add('validImageUpload', function (options) {
options.rules['validImageUpload'] = {};
options.messages['validImageUpload'] = options.message;
});
});