开发者

Dynamic validation on MVC 2

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:

Dynamic validation on MVC 2

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;
     开发者_如何学C       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:

Dynamic validation on MVC 2

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


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜