DataAnnotation Regular Expression始终为文件输入返回false

时间:2013-08-24 05:21:12

标签: asp.net-mvc asp.net-mvc-4

我为RegularExpression数据注释尝试了很多正则表达式,以检查文件扩展名是否为图像,并且它总是返回false,例如我还尝试了FileExtension属性,但它在jquery.validation上创建了一个错误。我使用的是ASP.NET MVC 4 Razor

[RegularExpression(@"^.*\.(jpg|gif|jpeg|png|bmp)$", 
ErrorMessage = "Please use an image with an extension of .jpg, .png, .gif, .bmp")]
public string MyImage { get; set; }

这是我的标记

    <div class="editor-field">            
        @Html.TextBoxFor(x => x.DepartmentImage, new { type = "file" })            
        @Html.ValidationMessage("DepartmentImageError")
        @Html.ValidationMessageFor(model => model.DepartmentImage)
    </div>

有人能告诉我如何让它发挥作用吗?

2 个答案:

答案 0 :(得分:11)

尝试修改如下代码。

@Html.ValidationMessageFor(model => model.MyImage)

我的建议

您的表单应如下所示。

@using (Html.BeginForm("Acion", "Conroller", FormMethod.Post, 
                                      new { enctype = "multipart/form-data" }))
{
    <input type="file" name="FileInfo" value="File to Upload" />
    @Html.ValidationMessageFor(I => I.FileInfo);
    <button type="submit" name="Upload" value="Upload" />
}

enter image description here

<强> HttpPostedFileBaseModelBinder

*如果 HttpPostedFileBase 的单个实例作为动作参数或模型中的属性,那么映射文件完全由 HttpPostedFileBaseModelBinder 完成,并且没有值提供者在这种情况下使用。你可能会想到为什么在这种情况下没有使用价值提供者,这是因为来源是单一且清晰的,即Request.Files集合。*

enter image description here

<强>模型

public class UploadFileModel
{
    [FileSize(10240)]
    [FileTypes("jpg,jpeg,png")]
    public HttpPostedFileBase FileInfo { get; set; }
}

enter image description here

<强> FileSizeAttribute

enter image description here

public class FileSizeAttribute : ValidationAttribute
{
    private readonly int _maxSize;

    public FileSizeAttribute(int maxSize)
    {
        _maxSize = maxSize;
    }

    public override bool IsValid(object value)
    {
        if (value == null) return true;

        return _maxSize > (value as HttpPostedFileBase).ContentLength;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format("The file size should not exceed {0}", _maxSize);
    }
}

<强> FileTypesAttribute

public class FileTypesAttribute: ValidationAttribute
{
    private readonly List<string> _types;

    public FileTypesAttribute(string types)
    {
        _types = types.Split(',').ToList();
    }

    public override bool IsValid(object value)
    {
        if (value == null) return true;

        var fileExt = System.IO
                            .Path
                            .GetExtension((value as
                                     HttpPostedFileBase).FileName).Substring(1);
        return _types.Contains(fileExt, StringComparer.OrdinalIgnoreCase);
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format("Invalid file type. Only the following types {0} 
                                    are supported.", String.Join(", ", _types));
    }
}

控制器操作方法

[HttpPost]
public ActionResult Upload(UploadFileModel fileModel)
{     
    if(ModelState.IsValid)
    {

    }

    return View(fileModel);
}

答案 1 :(得分:1)

为字段MyImage定义了RegularExpression,但您的@ValidationMessageFor验证了DepartmentImage。

这应该是

@Html.TextBoxFor(x => x.MyImage, new { type = "file" }) @Html.ValidationMessageFor(model => model.MyImage)