通过上传文件自定义客户端验证

时间:2014-03-28 19:21:22

标签: c# jquery asp.net-mvc client-side-validation

我使用客户端验证创建自己的数据注释,以检查所选文件是否被允许,但我无法使其工作。客户端方法没有被解雇。

我没有收到任何JavaScript错误。

型号:

public class FotoAlbumModel
{
    public int AlbumId { get; set; }

    [Filters.Required]
    [MaxLength(150, ErrorMessage = "Dit veld mag niet langer zijn dan 150 tekens.")]
    public string Titel { get; set; }

     [Filters.Required]
    [MaxLength(150, ErrorMessage = "Dit veld mag niet langer zijn dan 2500 tekens.")]
    public string Descriptie { get; set; }

    [Filters.Required]
    [MaxLength(250, ErrorMessage = "Dit veld mag niet langer zijn dan 250 tekens.")]
    public string Keywoorden { get; set; }

    [Filters.Required]
    [LinkName]
    public string Linknaam { get; set; }

    public bool Status { get; set; }

    public int AantalFotos { get; set; }

  [Filters.FileExtensions(FileExtensions = ".bmp,.jpg,.png.gif,.jpeg")]
    public HttpPostedFileBase[] Fotos { get; set; }
}

我的注释:

public class FileExtensionsAttribute : ValidationAttribute, IClientValidatable
{
    public string FileExtensions { get; set; }

    public override bool IsValid(object value)
    {
        string strValue = value == null ? "" : value.ToString();

        string[] arrayFileExtensions = FileExtensions.Split(',');

        bool isMatch = arrayFileExtensions.Any(x => x.Contains(Path.GetExtension(strValue)));

        if (!isMatch && ErrorMessage == null)
        {
            ErrorMessage = "De extensie van de bestand is niet toegestaan.";
        }
        return isMatch;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule
        {
            ErrorMessage = "De extensie van de bestand is niet toegestaan.",
            ValidationType = "fileextension"

        };
        rule.ValidationParameters.Add("allowedextensions", FileExtensions);

        yield return rule;
    }
}

我的自定义验证适配器:

$.validator.unobtrusive.adapters.addSingleVal("fileextension", "allowedextensions");

$.validator.addMethod("fileextension", function (value, element, allowedextensions) {
alert('sds');
var arrayAllowedExtensions = allowedextensions.split(',');
var fileExtension = value.split('.').pop();
$.each(arrayAllowedExtensions, function(extension) {
    if (extension == fileExtension) {
        return true;
    }
});
return false;
});

HTML:

   @Html.TextBoxFor(m=> m.Fotos, new {@type="file", @multiple="true", @onchange="makeFileList();", @id="filesToUpload", @style="display: none;"})
                                <input type="button" value="Plaatje(s) selecteren" class="btn btn-green btn-gradient" onclick="document.getElementById('filesToUpload').click();" />
                            <ul id="fileList">
                                <li>No Files Selected</li>
                            </ul>
                            @Html.ValidationMessageFor(m => m.Fotos)

MakeFileList Javascript函数:

<script>
    function makeFileList() {
        var input = document.getElementById("filesToUpload");
        var ul = document.getElementById("fileList");
        while (ul.hasChildNodes()) {
            ul.removeChild(ul.firstChild);
        }
        for (var i = 0; i < input.files.length; i++) {
            var li = document.createElement("li");
            li.innerHTML = input.files[i].name;
            ul.appendChild(li);
        }
        if(!ul.hasChildNodes()) {
            var li = document.createElement("li");
            li.innerHTML = 'No Files Selected';
            ul.appendChild(li);
        }
    }
</script>

为什么这个方法没有被解雇的任何想法?

2 个答案:

答案 0 :(得分:1)

我认为这是因为你隐藏了FileExtensionsAttribute代码试图验证的控件。

使用Firebug查看您的页面,您可以看到隐藏的控件<input id="filesToUpload" type="file"具有验证data-val-fileextension="De extensie van de bestand is niet toegestaan."

如果您通过删除@Html.TextBoxFor(m=> m.Fotos属性修改文本框@style="display: none;",则会看到您的验证有效。

不幸的是,我不确定如何解决这个问题。您是否有理由不能使用标准文件上传控件?

答案 1 :(得分:0)

更改@onchange="makeFileList();"上的:@Html.TextBoxFor(,, to:@onchange="makeFileList()"(删除末尾的分号)