File Extensions
The System.ComponentModel.DataAnnotations.FileExtensionsAttribute maps to the extension validation method in jquery validation additional-methods.js.
Note that this requires a wrapper attribute to work with the HttpPostedFileBase that is used to handle file uploads as the FileExtensionAttribute
expects a string to passed in.
Here's the model, note that the FileExtensions
attribute decorates the sole property on the model:
using System.ComponentModel.DataAnnotations; namespace jQuery.Validation.Unobtrusive.Native.Demos.Models { public class FileExtensionsModel { [FileExtensions(Extensions = "txt,pdf")] public string FileExtensions { get; set; } } }
Here's the view (which uses the model):
@model jQuery.Validation.Unobtrusive.Native.Demos.Models.FileExtensionsModel @using (Html.BeginForm()) { <div class="row"> @Html.LabelFor(x => x.FileExtensions, "Only a text file or PDF can be selected:") @Html.TextBoxFor(x => x.FileExtensions, true, htmlAttributes: new {type = "file"}) </div> <div class="row"> <button type="submit" class="btn btn-default">Submit</button> <button type="reset" class="btn btn-info">Reset</button> </div> }
Here's the HTML that the view generates:
<form action="/Demo/Email" method="post"> <div class="row"> <label for="FileExtensions">Only a text file can be selected:</label> <input data-msg-extension="The FileExtensions field only accepts files with the following extensions: .txt, .pdf" data-rule-extension="txt,pdf" id="FileExtensions" name="FileExtensions" type="file" value /> </div> <div class="row"> <button type="submit" class="btn btn-default">Submit</button> <button type="reset" class="btn btn-info">Reset</button> </div> </form>
Here's the JavaScript that initialises the validation:
<script type="text/javascript" src="/Scripts/additional-methods.min.js"></script> $("form").validate({ submitHandler: function (form) { alert("This is a valid form!"); } });