Client Side Validation Using Custom Validator FluentValidation MVC - asp.net-mvc

I have seen many examples of using FluentValidation here but none seem to fit my need. I have an existing server side implementation and based on answers here, I am convinced I have to change my implementation to get it work client side. One reason is because I can't set a ValidationType which seems required for the client side. I am having trouble converting the code so I can use it client side as well. I am submitting a list of File objects and want client side validation that the file extensions are either .pdf or .doc.
Global - Many examples here show a much more complicated Configure
protected void Application_Start()
{
FluentValidationModelValidatorProvider.Configure();
}
Model - I've simplified my model to show that I have at least one property and a collection
[Validator(typeof(MyCustomValidator))]
public class MyCustomModel
{
public DateTime SubmitDate { get; set; }
public List<HttpPostedFileBase> MyFiles { get; set; }
}
Model Validator - I have a separate validator for the collection
public class MyCustomModelValidator : AbstractValidator<MyCustomModel>
{
public MyCustomModelValidator()
{
RuleFor(x => x.SubmitDate)
.NotEmpty()
.WithMessage("Date Required");
RuleFor(x => x.MyFiles)
.SetCollectionValidator(new MyFileValidator())
.Where(x => x != null);
}
}
Collection Validator - This should check a file for a valid extension
public class MyFileValidator : AbstractValidator<HttpPostedFileBase>
{
public MyFileValidator()
{
RuleFor(x => x)
.Must(x => x.IsValidFileType())
.WithMessage("Invalid File Type")
}
}
public static bool IsValidFileType(this HttpPostedFileBase file)
{
var extensions = { ".pdf", ".doc" };
return extensions.Contains(Path.GetExtension(file.FileName.ToLower()));
}
Controller - Just showing the basics
[HttpGet]
public ActionResult Index(DefaultParameters parameters)
{
var model = new MyCustomModel();
return this.View(model);
}
[HttpPost]
public ActionResult Submit(MyCustomModel model)
{
if (!ModelState.IsValid)
{
return this.View("Index", model);
}
}
View - I am allowing 5 uploads per submission
#Html.TextBoxFor(m => m.SubmitDate)
#Html.ValidationMessageFor(m => m.TextBoxFor
#for (int i = 0; i < 5; i++)
{
#Html.TextBoxFor(m => m.FileSubmissions[i], new { type = "file" })
#Html.ValidationMessageFor(m => m.FileSubmissions[i])
}

Im not sure why you would change it to clientside? Not all validations should run clientside. Maybe you can get it working using the regex validation method instead of the Must method which is performed clientside according to the docs.

Related

Correct way to display a list in a dropdown using mvc

I know there are a lot of similar question here but none seem quite the same as mine.
In my View:
#model LocalInformedMotionServer.Models.FeedData
#Html.DropDownList("Premise", Model.LoadUp("key"), new { #style = "width: 218px;height:35px;" })
In my controller:
public class CloudController : Controller
{
public IEnumerable<wsCommon.Premise> Premises { get; set; }
public ActionResult Feed(string key)
{
var feedData = new FeedData();
Premises= feedData.LoadUp(key);
return View(feedData);
}
}
In my Model:
public class FeedData
{
public IEnumerable<wsCommon.Premise> LoadUp(string saltKey)
{
Premises premises = new InformedBiz.Premises();
return premises.GetPremises(saltKey);
}
}
It errors because the variable:
"key"
in this call:
Model.LoadUp("key")
is being read in as'null' in my controller method.
Of course as this is all new to me I could be doing this all wrong..
ADDITIONAL:
In my CloudController Class I have this:
public class CloudController : Controller
{
public ActionResult Feed(string saltKey)
{
var feedData = new FeedData();
feedData.LoadUp(saltKey);
return View(feedData);
}
public ActionResult Index()
{
return View();
}
public ActionResult LogIn()
{
return View();
}
}
I'm not sure what your Premise class looks like, but I usually use an IEnumberable of SelectListItem for drop downs in my views. So you could do something like this:
public IEnumerable<SelectListItem> LoadUp(string saltKey)
{
Premises premises = new InformedBiz.Premises();
return premises.GetPremises(saltKey).Select(
p => new SelectListItem { Text = p.Name, Value = z.PremiseId.ToString() }
);
}
You'll also need to create a Post ActionResult method that accepts the model in your view (FeedData) as well as wrap your DropDownList control in a Html.BeginForm, to post results to the controller. Hope this makes a bit of sense.
You have not posted the properties of your FeedData model but assuming it contains a property which is typeof Premise and you want to be able to select a Premise from a collection, then using a view model that represents what you want to display/edit is the recommended approach (refer View Model Design And Use In Razor Views and What is ViewModel in MVC?)
You view model might look like
public class FeedDataVM
{
.....
[Display(Name = "Premise")]
[Required(ErrorMessage = "Please select a Premise")]
public int? SelectedPremise { get; set; }
....
public SelectList PremiseList { get; set; }
}
and in your controller (not sure what saltKey is for?)
public ActionResult Feed(string saltKey)
{
FeedDataVM model = new FeedDataVM();
IEnumerable<Premise> premises = // get the collection of premise objects from your repository
// assuming you want to display the name property of premise, but post back the key property
model.PremiseList = new SelectList(premises, "key", "name");
return View(model);
}
View
#model FeedDataVM
#using(Html.BeginForm())
{
....
#Html.LabelFor(m => m.SelectedPremise)
#Html.DropDownListFor(m => m.SelectedPremise, Model.PremiseList, "-Please select")
#Html.ValidationMessageFor(m => m.SelectedPremise)
....
<input type="submit" value="Save" />
}
and the POST method
public ActionResult Feed(FeedDataVM model)
{
// model.SelectedPremise contains the value of the selected option as defined by the key property of Premise
}
Side note: Your FeedData model contains a method to retrieve a collection of Premise which appears to be calling another service. You should avoid this type of design which makes it difficult to debug and unit test. Your controller is responsible for initializing/getting you data models and view models and for populating/mapping their properties.

Fluent Validation in MVC: specify RuleSet for Client-Side validation

In my ASP.NET MVC 4 project I have validator for one of my view models, that contain rules definition for RuleSets. Edit ruleset used in Post action, when all client validation passed. Url and Email rule sets rules used in Edit ruleset (you can see it below) and in special ajax actions that validate only Email and only Url accordingly.
My problem is that view doesn't know that it should use Edit rule set for client html attributes generation, and use default rule set, which is empty. How can I tell view to use Edit rule set for input attributes generation?
Model:
public class ShopInfoViewModel
{
public long ShopId { get; set; }
public string Name { get; set; }
public string Url { get; set; }
public string Description { get; set; }
public string Email { get; set; }
}
Validator:
public class ShopInfoViewModelValidator : AbstractValidator<ShopInfoViewModel>
{
public ShopInfoViewModelValidator()
{
var shopManagementService = ServiceLocator.Instance.GetService<IShopService>();
RuleSet("Edit", () =>
{
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Enter name.")
.Length(0, 255).WithMessage("Name length should not exceed 255 chars.");
RuleFor(x => x.Description)
.NotEmpty().WithMessage("Enter name.")
.Length(0, 10000).WithMessage("Name length should not exceed 10000 chars.");
ApplyUrlRule(shopManagementService);
ApplyEmailRule(shopManagementService);
});
RuleSet("Url", () => ApplyUrlRule(shopManagementService));
RuleSet("Email", () => ApplyEmailRule(shopManagementService));
}
private void ApplyUrlRule(IShopService shopService)
{
RuleFor(x => x.Url)
.NotEmpty().WithMessage("Enter url.")
.Length(4, 30).WithMessage("Length between 4 and 30 chars.")
.Matches(#"[a-z\-\d]").WithMessage("Incorrect format.")
.Must((model, url) => shopService.Available(url, model.ShopId)).WithMessage("Shop with this url already exists.");
}
private void ApplyEmailRule(IShopService shopService)
{
// similar to url rule: not empty, length, regex and must check for unique
}
}
Validation action example:
public ActionResult ValidateShopInfoUrl([CustomizeValidator(RuleSet = "Url")]
ShopInfoViewModel infoViewModel)
{
return Validation(ModelState);
}
Get and Post actions for ShopInfoViewModel:
[HttpGet]
public ActionResult ShopInfo()
{
var viewModel = OwnedShop.ToViewModel();
return PartialView("_ShopInfo", viewModel);
}
[HttpPost]
public ActionResult ShopInfo(CustomizeValidator(RuleSet = "Edit")]ShopInfoViewModel infoViewModel)
{
var success = false;
if (ModelState.IsValid)
{
// save logic goes here
}
}
View contains next code:
#{
Html.EnableClientValidation(true);
Html.EnableUnobtrusiveJavaScript(true);
}
<form class="master-form" action="#Url.RouteUrl(ManagementRoutes.ShopInfo)" method="POST" id="masterforminfo">
#Html.TextBoxFor(x => x.Name)
#Html.TextBoxFor(x => x.Url, new { validationUrl = Url.RouteUrl(ManagementRoutes.ValidateShopInfoUrl) })
#Html.TextAreaFor(x => x.Description)
#Html.TextBoxFor(x => x.Email, new { validationUrl = Url.RouteUrl(ManagementRoutes.ValidateShopInfoEmail) })
<input type="submit" name="asdfasfd" value="Сохранить" style="display: none">
</form>
Result html input (without any client validation attributes):
<input name="Name" type="text" value="Super Shop"/>
After digging in FluentValidation sources I found solution. To tell view that you want to use specific ruleset, decorate your action, that returns view, with RuleSetForClientSideMessagesAttribute:
[HttpGet]
[RuleSetForClientSideMessages("Edit")]
public ActionResult ShopInfo()
{
var viewModel = OwnedShop.ToViewModel();
return PartialView("_ShopInfo", viewModel);
}
If you need to specify more than one ruleset — use another constructor overload and separate rulesets with commas:
[RuleSetForClientSideMessages("Edit", "Email", "Url")]
public ActionResult ShopInfo()
{
var viewModel = OwnedShop.ToViewModel();
return PartialView("_ShopInfo", viewModel);
}
If you need to decide about which ruleset would be used directly in action — you can hack FluentValidation by putting array in HttpContext next way (RuleSetForClientSideMessagesAttribute currently is not designed to be overriden):
public ActionResult ShopInfo(validateOnlyEmail)
{
var emailRuleSet = new[]{"Email"};
var allRuleSet = new[]{"Edit", "Url", "Email"};
var actualRuleSet = validateOnlyEmail ? emailRuleSet : allRuleSet;
HttpContext.Items["_FV_ClientSideRuleSet"] = actualRuleSet;
return PartialView("_ShopInfo", viewModel);
}
Unfortunately, there are no info about this attribute in official documentation.
UPDATE
In newest version we have special extension method for dynamic ruleset setting, that you should use inside your action method or inside OnActionExecuting/OnActionExecuted/OnResultExecuting override methods of controller:
ControllerContext.SetRulesetForClientsideMessages("Edit", "Email");
Or inside custom ActionFilter/ResultFilter:
public class MyFilter: ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
((Controller)context.Controller).ControllerContext.SetRulesetForClientsideMessages("Edit", "Email");
//same syntax for OnActionExecuted/OnResultExecuting
}
}
Adding to this as the library has been updated to account for this situation...
As of 7.4.0, it's possible to dynamically select one or multiple rule sets based on your specific conditions;
ControllerContext.SetRulesetForClientsideMessages("ruleset1", "ruleset2" /*...etc*);
Documentation on this can be found in the latest FluentValidation site:
https://fluentvalidation.net/aspnet#asp-net-mvc-5
Adding the CustomizeValidator attribute to the action will apply the ruleset within the pipeline when the validator is being initialized and the model is being automatically validated.
public ActionResult Save([CustomizeValidator(RuleSet="MyRuleset")] Customer cust) {
// ...
}

.NET MVC Custom validation (without data annotation)

use .NET MVC and code-first EF to implement of requested functionality. Business objects are relatively complex and I use System.ComponentModel.DataAnnotations.IValidatableObject to validate business object.
Now I'm trying to find the way, how to show validation result from business object, using MVC ValidationSummary without using data annotations. For example (very simplified):
Business Object:
public class MyBusinessObject : BaseEntity, IValidatableObject
{
public virtual IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
return Validate();
}
public IEnumerable<ValidationResult> Validate()
{
List<ValidationResult> results = new List<ValidationResult>();
if (DealType == DealTypes.NotSet)
{
results.Add(new ValidationResult("BO.DealType.NotSet", new[] { "DealType" }));
}
return results.Count > 0 ? results.AsEnumerable() : null;
}
}
Now in my MVC controller I have something like this:
public class MyController : Controller
{
[HttpPost]
public ActionResult New(MyModel myModel)
{
MyBusinessObject bo = GetBoFromModel(myModel);
IEnumerable<ValidationResult> result = bo.Validate();
if(result == null)
{
//Save bo, using my services layer
//return RedirectResult to success page
}
return View(myModel);
}
}
In view, I have Html.ValidationSummary();.
How I can pass IEnumerable<ValidationResult> to the ValidationSummary?
I tried to find an answer by googling, but all examples I found describes how to show validation summary using data annotations in Model and not in Business object.
Thanks
Add property, say BusinessError, in the model
in the View do the following
#Html.ValidationMessageFor(model => model.BusinessError)
Then in your controller whenever you have error do the following
ModelState.AddModelError("BussinessError", your error)
I would have a look at FluentValidation. It's a framework for validation without data annoations. I've used it with great success in some projects for complex validation, and it is also usable outside of the MVC-project.
Here is the sample code from their page:
using FluentValidation;
public class CustomerValidator: AbstractValidator<Customer> {
public CustomerValidator() {
RuleFor(customer => customer.Surname).NotEmpty();
RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(customer => customer.Company).NotNull();
RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
RuleFor(customer => customer.Address).Length(20, 250);
RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
}
private bool BeAValidPostcode(string postcode) {
// custom postcode validating logic goes here
}
}
Customer customer = new Customer();
CustomerValidator validator = new CustomerValidator();
ValidationResult results = validator.Validate(customer);
bool validationSucceeded = results.IsValid;
IList<ValidationFailure> failures = results.Errors;
Entity Framework should throw a DbEntityValidationException if there are validation errors. You can then use the exception to add the errors to the ModelState.
try
{
SaveChanges();
}
catch (DbEntityValidationException ex)
{
AddDbErrorsToModelState(ex);
}
return View(myModel);
protected void AddDbErrorsToModelState(DbEntityValidationException ex)
{
foreach (var validationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
ModelState.AddModelError(validationError.PropertyName, validationError.ErrorMessage);
}
}
}
One of the ways to pass the contents of IEnumerate and keep taking advantage of Html.ValidationSummary is by updating ModelState.
You can find a good discussion on how to update the ModelState here.

KendoUI MVC Json - do they work together?

I am client-server, SQL programmer (RAD guy) and the company decided that we must move to .NET environment. We are examining the platform now.
I studied the MVC4 and the Entities Framework this week and I have read a lot about KendoUI. I was skeptical because most of the examples come with KendoGrid+WebApi. I know awfully little about WebApi but I really liked the Entities thing a lot so I do not think I should give it a chance.
I want to ask some question which may seem naive but the answers will help me a lot
Once I create entities from an existing database, can I have the results in Json format and with this to feed a KendoGrid?
If yes, how? I mean:
How I can convert the results in Json inside the Controller?
In the transport property of the KendoGrid I should put the URL of the Controller/Action?
and the most naive one
Does Telerik have any thoughts of providing a visual tool to create-configure the kendoGrid? To make it more RAD because now need TOO MUCH coding. Maybe a wizard that you can connect entities with Grid columns, datasource, transport selectors etc..
I hope you choose the Kendo Entities path, there will be a learning curve though. No, on question 4. But let me give you a jump start using the Razor view engine and answer 1, 2, and 3.
First, EF is creating business objects. You 'should' convert these to Models in MVC. In this example Person is from EF. I think of this as flattening because it removes the depth from the object, though it i still available so you could reference something like Person.Titles.Name if your database was setup like that. You can also drop in DataAnnotations, which just rock.
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Project.Business;
namespace Project.Web.Models
{
public class PersonModel
{
public int Id { get; set; }
[Required(ErrorMessage = "Last Name is required.")]
public string LastName { get; set; }
[Required(ErrorMessage = "First Name is required.")]
public string FirstName { get; set; }
[Display(Name = "Created")]
public System.DateTime StampCreated { get; set; }
[Display(Name = "Updated")]
public System.DateTime StampUpdated { get; set; }
[Display(Name = "Enabled")]
public bool IsActive { get; set; }
public PersonModel()
{}
public PersonModel(Person person)
{
Id = person.Id;
FirstName = person.FirstName;
LastName = person.LastName;
StampCreated = person.StampCreated;
StampUpdated = person.StampUpdated;
IsActive = person.IsActive;
}
public static IList<PersonModel> FlattenToThis(IList<Person> people)
{
return people.Select(person => new PersonModel(person)).ToList();
}
}
}
Moving along...
#(Html.Kendo().Grid<PersonModel>()
.Name("PersonGrid")
.Columns(columns => {
columns.Bound(b => b.Id).Hidden();
columns.Bound(b => b.LastName).EditorTemplateName("_TextBox50");
columns.Bound(b => b.FirstName).EditorTemplateName("_TextBox50");
columns.Bound(b => b.StampUpdated);
columns.Bound(b => b.StampCreated);
columns.Bound(b => b.IsActive).ClientTemplate("<input type='checkbox' ${ IsActive == true ? checked='checked' : ''} disabled />").Width(60);
columns.Command(cmd => { cmd.Edit(); cmd.Destroy(); }).Width(180);
})
.ToolBar(toolbar => toolbar.Create())
.Pageable()
.Filterable()
.Sortable()
.Selectable()
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Error("error_handler"))
.Model(model =>
{
model.Id(a => a.Id);
model.Field(a => a.StampCreated).Editable(false);
model.Field(a => a.StampUpdated).Editable(false);
model.Field(a => a.IsActive).DefaultValue(true);
})
.Create(create => create.Action("CreatePerson", "People"))
.Read(read => read.Action("ReadPeople", "People"))
.Update(update => update.Action("UpdatePerson", "People"))
.Destroy(destroy => destroy.Action("DestroyPerson", "People"))
.PageSize(10)
)
)
Those _TextBox50 are EditorTemplates named _TextBox50.cshtml that MUST go either in a subfolder relative to your view or relative to your Shared folder - the folder must be called EditorTemplates. This one looks like this...
#Html.TextBox(string.Empty, string.Empty, new { #class = "k-textbox", #maxlength = "50" })
Yes, thats all. This is a simple example, they can get much more complicated. Or you don't have to use them initially.
And finally, what I think you are really looking for...
public partial class PeopleController : Controller
{
private readonly IPersonDataProvider _personDataProvider;
public PeopleController() : this(new PersonDataProvider())
{}
public PeopleController(IPersonDataProvider personDataProvider)
{
_personDataProvider = personDataProvider;
}
public ActionResult Manage()
{
>>> Left in as teaser, good to apply a special Model to a View to pass goodies ;)
var model = new PeopleViewModel();
model.AllQualifications = QualificationModel.FlattenToThis(_qualificationDataProvider.Read());
return View(model);
}
[HttpPost]
public JsonResult CreatePerson([DataSourceRequest]DataSourceRequest request, Person person)
{
if (ModelState.IsValid)
{
try
{
person = _personDataProvider.Create(person);
}
catch (Exception e)
{
ModelState.AddModelError(string.Empty, e.InnerException.Message);
}
}
var persons = new List<Person> {person};
DataSourceResult result = PersonModel.FlattenToThis(persons).ToDataSourceResult(request, ModelState);
return Json(result, JsonRequestBehavior.AllowGet);
}
public JsonResult ReadPeople([DataSourceRequest]DataSourceRequest request)
{
var persons = _personDataProvider.Read(false);
DataSourceResult result = PersonModel.FlattenToThis(persons).ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult UpdatePerson([DataSourceRequest]DataSourceRequest request, Person person)
{
if (ModelState.IsValid)
{
try
{
person = _personDataProvider.Update(person);
}
catch (Exception e)
{
ModelState.AddModelError(string.Empty, e.InnerException.Message);
}
}
var persons = new List<Person>() {person};
DataSourceResult result = PersonModel.FlattenToThis(persons).ToDataSourceResult(request, ModelState);
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public JsonResult DestroyPerson([DataSourceRequest]DataSourceRequest request, Person person)
{
if (ModelState.IsValid)
{
try
{
person = _personDataProvider.Destroy(person);
}
catch (Exception e)
{
ModelState.AddModelError(string.Empty, "There was an error deleting this record, it may still be in use.");
}
}
var persons = new List<Person>() {person};
DataSourceResult result = PersonModel.FlattenToThis(persons).ToDataSourceResult(request, ModelState);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
Notice that, in this case, each method takes the EF Person as a parameter, it would be better to use PersonModel but then I would have to show the opposite of the Flatten. This works becuase they are practically identical. If the model was different or you were using a class factory it gets a bit more tricky.
I intentionally showed you all the CRUD operations. If you don't pass the result back to the grid it will act funny and give you dupicates or not show updates correctly on CREATE and UPDATE. It is passed back on DELETE to pass the ModelState which would have any errors.
And finally the data provider, so as to leave nothing to the imagination...
(Namespace declaration omited.)
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Linq;
using Project.Business;
public class PersonDataProvider : ProviderBase, IPersonDataProvider
{
public Person Create(Person person)
{
try
{
person.StampCreated = DateTime.Now;
person.StampUpdated = DateTime.Now;
Context.People.Attach(person);
Context.Entry(person).State = EntityState.Added;
Context.SaveChanges();
return person;
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
throw;
}
}
public IList<Person> Read(bool showAll)
{
try
{
return (from q in Context.People
orderby q.LastName, q.FirstName, q.StampCreated
where (q.IsActive == true || showAll)
select q).ToList();
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
throw;
}
}
...
}
Note the Interface and ProviderBase inheritance, you have to make those. Should be simple enough to find examples.
This may seem like a lot of coding, but once you get it down, just copy paste.
Happy coding.
yes you can send the JSON back kendo UI using the JsonResult or using the JSON with allow get specified. you can set the url in the transport and specify the json as the type.
About your last question there is no visual tools right now but there are helper methods available for kendo UI

MVC3 Custom Unobtrusive Validator on a List of Objects

The basic question to start: How can you put a custom, unobtrusive validator ontop of a list of objects within your model? Like, say my model allows multiple file uploads, and thus I have a list of files, and I want my validator to run on each of those files?
Now for a specific example. I've got a custom, unobtrusive validator that checks to see if a file extension is not within a list of prohibited extensions:
public class FileExtensionValidatorAttribute : ValidationAttribute, IClientValidatable {
protected static string[] PROHIBITED_EXTENSIONS = {
// ... List of extensions I don't allow.
};
public override bool IsValid(object value) {
if (value is IEnumerable<HttpPostedFileBase>) {
foreach (var file in (IEnumerable<HttpPostedFileBase>)value) {
var fileName = file.FileName;
if (PROHIBITED_EXTENSIONS.Any(x => fileName.EndsWith(x))) return false;
}
} else {
var file = (HttpPostedFileBase)value;
var fileName = file.FileName;
if (PROHIBITED_EXTENSIONS.Any(x => fileName.EndsWith(x))) return false;
}
return true;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) {
var modelClientVlidationRule = new ModelClientValidationRule {
ErrorMessage = this.ErrorMessageString,
ValidationType = "fileextension",
};
modelClientVlidationRule.ValidationParameters.Add("prohibitedextensions", string.Join("|", PROHIBITED_EXTENSIONS));
yield return modelClientVlidationRule;
}
}
Take note in my IsValid that I built this to accept a single file or a list of files.
In my model class, I can make use of this on a single HttpPostedFileBase:
[FileExtensionValidator(ErrorMessage = "Invalid Extension")]
public HttpPostedFileBase Upload { get; set; }
Then I attach to jquery's validator in my view:
jQuery.validator.addMethod("fileExtension", function (value, element, param) {
var extension = "";
var dotIndex = value.lastIndexOf('.');
if (dotIndex != -1) extension = value.substring(dotIndex + 1).toLowerCase();
return $.inArray(extension, param.prohibitedExtensions) === -1;
});
jQuery.validator.unobtrusive.adapters.add('fileextension', ['prohibitedextensions'], function (options) {
options.rules['fileExtension'] = {
prohibitedExtensions: options.params.prohibitedextensions.split('|')
};
options.messages['fileExtension'] = options.message;
});
This all works great, client side and server side ...but only on a single HttpPostedFileBase. The problem is that I need to provide users the ability to upload one or more files. If I change my model to this:
[FileExtensionValidator(ErrorMessage = "Invalid Extension")]
public List<HttpPostedFileBase> Uploads { get; set; }
...the Client-side validation no longer runs; only the server-side works. This is evident when doing a view-source. The <input> tag that gets generated is missing all the data-val attributes it needs to run. In doing a debug, GetClientValidationRules is never called.
What am I missing?
Could this be because of how I render it? I'm simply using an EditorTemplate for HttpPostedFileBase:
#model System.Web.HttpPostedFileBase
#Html.TextBoxFor(m => m, new { type = "file", size = 60 })
...and my view renders it like this:
<p>#Html.EditorFor(m => m.Uploads)</p>
Any advice is appreciated.
Here's what I came up with.
I actually think the problem is ultimately caused because MVC doesn't know that I want that Data Annotation on the List to be applied to all of its members. Nor should it I suppose.
So I simply made a "viewmodel" wrapper around HttpPostedFileBase, and put my validator there:
public class UploadedFile {
[FileExtensionValidator(ErrorMessage = "Invalid Extension")]
public HttpPostedFileBase File { get; set; }
}
Then, in my actual model, I now just use a list of those instead:
public List<UploadedFile> Uploads { get; set; }
...with no more dataannotations here of course since they're now in UploadedFile.
Then, with minor modifications to the view and editortemplate to use these, this now works a-ok, client side and server side. (Still, feels clunky to me. If anyone has a simpler way I'm still happy to hear it.)

Resources