我已经通过这个链接在我的应用程序中实现了复杂的自定义 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)