1

我已经通过这个链接在我的应用程序中实现了复杂的自定义 Foolproof 验证,但遗憾的是它不起作用。我的要求很简单,我有一个用于上传图像的文件,如果用户选择上传以下指定以外的文件input file,则应该有一个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)
4

1 回答 1

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; }
于 2015-10-27T07:44:21.547 回答