万无一失的验证中的复杂自定义验证

时间:2015-10-26 12:49:29

标签: validation foolproof-validation

我已经在this link的应用程序中实现了复杂的自定义Foolproof验证,但遗憾的是它不起作用。我的要求很简单,我有一个input file用于上传图像,应该有一个{{1如果用户选择上传除下面指定的文件以外的文件

validation

代码

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

CSHTML

    [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;

    }
}

1 个答案:

答案 0 :(得分: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; }