2015-10-26 3 views
1
защиты от случайных ошибок

Я реализовал комплекс пользовательского Foolproof проверки в моем приложении от this link, но, к сожалению, его не working.My требования просто, у меня есть input file для загрузки изображения и должен быть validation, если пользователь выбирает загрузить файл, кроме указанных нижекомплексов Пользовательских проверок в Validation

  ".jpg",".png",".gif",".jpeg" 

кодекса

[Required(ErrorMessage = "Please upload Photo", AllowEmptyStrings = false)] 
    [IsValidPhoto(ErrorMessage="Please select files of type .jpg,.png,.gif,.jpeg")] 
    public HttpPostedFileBase PhotoUrl { get; set; } 

public class IsValidPhotoAttribute : ModelAwareValidationAttribute 
{ 
    //this is needed to register this attribute with foolproof's validator adapter 
    static IsValidPhotoAttribute() { Register.Attribute(typeof(IsValidPhotoAttribute)); } 

    public override bool IsValid(object value, object container) 
    { 
     if (value != null) 
     { 
      string[] AllowedFileExtensions = new string[] { ".jpg", ".gif", ".png", ".jpeg" }; 
      var file = value as HttpPostedFileBase; 


      if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.')))) 
      { 
       return false; 
      } 


     } 
     return true; 

    } 
} 

CSHTML является

@Html.TextBoxFor(m => m.PhotoUrl, new { @class = "form-control imgUpload", 
@placeholder = "Please upload Photo", @id = "txtPhoto", @type = "file" }) 
@Html.ValidationMessageFor(m => m.PhotoUrl) 
+0

Только использование тег jQuery Validate, когда ваш вопрос касается плагина jQuery Validate. Ред. – Sparky

ответ

2

Вы не сможете получить подтверждение на стороне клиента, если вы также создать скрипт для добавления правила. Нет необходимости использовать несложный и следующий метод и скрипты даст вам сервера и на стороне клиента Валидация ОБА

public class FileAttachmentAttribute : ValidationAttribute, IClientValidatable 
{ 
    private List<string> _Extensions { get; set; } 
    private const string _DefaultErrorMessage = "Only file types with the following extensions are allowed: {0}"; 
    public FileAttachmentAttribute(string fileExtensions) 
    { 
    _Extensions = fileExtensions.Split('|').ToList(); 
    ErrorMessage = _DefaultErrorMessage; 
    } 

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
    HttpPostedFileBase file = value as HttpPostedFileBase; 
    if (file != null) 
    { 
     var isValid = _Extensions.Any(e => file.FileName.EndsWith(e)); 
     if (!isValid) 
     { 
     return new ValidationResult(string.Format(ErrorMessageString, string.Join(", ", _Extensions))); 
     } 
    } 
    return ValidationResult.Success; 
    } 

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) 
    { 
    var rule = new ModelClientValidationRule 
    { 
     ValidationType = "fileattachment", 
     ErrorMessage = string.Format(ErrorMessageString, string.Join(", ", _Extensions)) 
    }; 
    rule.ValidationParameters.Add("extensions", string.Join(",", _Extensions)); 
    yield return rule; 
    } 
} 

скрипты

$.validator.unobtrusive.adapters.add('fileattachment', ['extensions'], function (options) { 
    var params = { fileattachment: options.params.extensions.split(',') }; 
    options.rules['fileattachment'] = params; 
    if (options.message) { 
    options.messages['fileattachment'] = options.message; 
    } 
}); 

$.validator.addMethod("fileattachment", function (value, element, param) { 
    var extension = getExtension(value); 
    return $.inArray(extension, param.fileextensions) !== -1; 
}); 

function getExtension(fileName) { 
    var extension = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined; 
    if (extension != undefined) { 
    return extension[0]; 
    } 
    return extension; 
}; 

, а затем использовать его в качестве

[FileAttachment("jpg|gif|png|jpeg")] 
public HttpPostedFileBase PhotoUrl { get; set; } 
+0

Спасибо за вашу замечательную поддержку .. :) – ksg