简体   繁体   English

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

[英]Custom client side validation with uploading a file

I'm creating my own data annotation with client side validation to check if the chosen files are allowed, but i can't get it to work. 我正在使用客户端验证创建自己的数据注释,以检查是否允许选择的文件,但我无法使其正常工作。 The client side method doesn't get fired up. 客户端方法不会启动。

I'm not getting any JavaScript errors. 我没有收到任何JavaScript错误。

Model: 模型:

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

My annotation: 我的注释:

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

My custom validation adapter: 我的自定义验证适配器:

$.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:

   @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 function: 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>

Any ideas why the method is not being fired up? 有什么想法为什么不启动该方法?

I think this is because you're hiding the control that the FileExtensionsAttribute code is trying to validate. 我认为这是因为您要隐藏FileExtensionsAttribute代码试图验证的控件。

Look at your page using Firebug, and you can see that the hidden control <input id="filesToUpload" type="file" has the validation data-val-fileextension="De extensie van de bestand is niet toegestaan." 使用Firebug查看您的页面,您可以看到隐藏的控件<input id="filesToUpload" type="file"具有验证data-val-fileextension="De extensie van de bestand is niet toegestaan."

If you modify your textbox @Html.TextBoxFor(m=> m.Fotos by removing the @style="display: none;" attribute, you'll see that your validation works. 如果通过删除@style="display: none;"属性来修改文本框@Html.TextBoxFor(m=> m.Fotos ,您将看到您的验证有效。

Unfortunately I'm not sure how to get round this problem. 不幸的是,我不确定如何解决这个问题。 Is there a reason you can't use the standard file upload control? 您有理由不能使用标准文件上传控件吗?

change the: @onchange="makeFileList();" 更改: @onchange="makeFileList();" on @Html.TextBoxFor(,, to: @onchange="makeFileList()" (remove the semi-colon at the end) @Html.TextBoxFor(,,上: @onchange="makeFileList()" (最后删除分号)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM