Dynamic validation on MVC 2

2019-04-12 00:20发布

问题:

This works fine

 [MetadataType(typeof(Area_Validation))]
 public partial class Area
 {
    ...
 }

 public class Area_Validation
 {
 [Required(ErrorMessage = "Please add this field.")] 
 public int Email { get; set; }

 [Required(ErrorMessage = "Please add this field")]
 public string Name { get; set; }
 }

but how about if Area_Validation is dynamically created? for example Subscription Fields that on back-end can be created by the user and end up like this:

How can I set the Metadata on each field for auto validation?

Currently I'm doing:

public class SubscriberFormViewModel
{
    public List<SubscriberFieldModel> Fields { get; private set; }
    public Calendar Calendar { get; private set; }
    public Company Company { get; private set; }

    public SubscriberFormViewModel()
    { 
        // TODO: This is only for testing while validation is not set
    }
    public SubscriberFormViewModel(Decimal calendarId)
    {
        if (calendarId > 0)
        {
            SubscribersRepository db = new SubscribersRepository();

            Calendar calendar = db.GetCalendarById(calendarId);
            Company company = db.GetCompanyById(calendar.company_id);

            this.Fields = db.FindAllSubscriberFieldsByCalendar(calendarId);
            this.Calendar = calendar;
            this.Company = company;
        }
        else
            this.Fields = new List<SubscriberFieldModel>();
    }
}

and I want to set the Metadata in all Fields property

In other words, this Fields are filled up from the Database and can have several types, can be a string, number, dropdown, etc ... kinda like MailChimp Fields Properties:

is there a way to do this programmaticaly or I need to create a jQuery plugin to validate it and stop using use validation from MVC2 ?

Thank you

回答1:

I dont think you can do this using Data Annotations attributes.

There is a project in Codeplex, called Fluent Validation that permit you to add validation rules in a fluent way using .Net code. I never used that project but it seems that maybe can help you in your case with dynamically created objects.

Hope it helps!



回答2:

Actually you can make several validation scenarios, one per type(or more per type if you need). Then Add this validation rules on type creation. When you need to validate, you can call template Validate method, that will check if these rules and if not - will add errors to ModelState, that you will be able to show on front end.

Actually its not that profitable to add any attributes, as attributes pro is that you can decorate your type with them. When you are doing some dynamic things, you`d better have some dynamic way to add validation.