提问人:race155 提问时间:6/10/2016 最后编辑:race155 更新时间:6/10/2016 访问量:1205
使用 jQuery 非侵入式验证进行文件类型和扩展名验证
File type and extension validation with jQuery unobtrusive validation
问:
我目前正在尝试验证将上传到页面上的文件。我希望能够验证文件类型是 .doc、.docx、.txt、.pdf、.rtf 以及大小是否为 4 mb 或更小。我尝试使用正则表达式通过以下代码验证类型。
[RegularExpression(@"(^.*\.(rtf|doc|docx|pdf)$", ErrorMessage =@"Please upload a (.pdf, .doc, .docx, .txt, or .rtf) file")]
然后,我尝试通过创建以下类来验证文件大小和类型
public class ValidateFileAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
int MaxContentLength = 1024;
string[] AllowedFileExtensions = new string[] { ".doc", ".docx", ".pdf", ".txt", ".rtf" };
var file = value as HttpPostedFileBase;
if (file == null)
return false;
else if (!AllowedFileExtensions.Contains(file.FileName.Substring(file.FileName.LastIndexOf('.'))))
{
ErrorMessage = "Upload File Type: " + string.Join(", ", AllowedFileExtensions);
return false;
}
else if (file.ContentLength > MaxContentLength)
{
ErrorMessage = "The Size of the file is too large : " + (MaxContentLength / 1024).ToString() + "MB";
return false;
}
else
return true;
}
}
(我知道 1024 不允许我上传一个非常大的文件,但出于测试原因,我把它留在那里,看看它是否有效)。
在我使用的视图中@Html.TextBoxFor(m => m.CV.File, new { type="file"})
@Html.ValidationMessageFor(m => m.CV.File)
我不确定如何让验证正常工作,它不允许我输入不同的文件类型,但是,它也无法识别正确的文件类型。
答: 暂无答案
评论
[FileSize(1024)]
[FileType("rtf|doc|docx|pdf")]
FileSizeAttribute
FileTypeAttribute
IClientValidatable
jQuery.validator
protected override Validation Result
public FileTypeAttribute(string validTypes)
return ValidationResult.Success;