Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

alt text

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:

alt text

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

like image 451
balexandre Avatar asked May 05 '26 09:05

balexandre


1 Answers

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.

like image 70
Yaroslav Yakovlev Avatar answered May 11 '26 03:05

Yaroslav Yakovlev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!