Validation of dynamic fields in a MVC

2019-04-11 04:22发布

问题:

My model looks like

public class Template
{
    Id
    Title
    List<Field> Fields
}

The “Field” Entity contains information like Name, Caption, Type (TextBox/Select/Radio), Options, and validation rules (Range, Required, string length).

The standard validation in MVC is based on DataAnnotations, but I wants to validate (Both client and Server Side) the form dynamically based on Field Metadata which is dynamic and configurable.

Is it possible? Any pointers?

PS. I searched for the similar questions, but not able to find a solid answer.

回答1:

I had a similar situation, this is how I handled it:

Server Side

When the POST happened I iterated over all the Fields values and did the Validation based on the validation rules I had on my objects. Then you can simply add ModelErrors to the Field object.

Since you push a Template object to the View you can access the Fields by name Fields[x].SomeProperty. Make sure you have a ValidationMessageFor for SomeProperty

ModelState.AddModelError("Fields[x].SomeProperty", "The Error Message you want to show.);

Client side

Make sure your form has an Id so you can access the Validate method(). Then you iterate over all the fields and just add the validation as you please.

For all the validations rules check the validation Jquery documentation.

    $('#frmYourForm').validate();
        for (var i = 0; i < 'CountOfAllFields'; i++)
        {
            $('#Fields_' + i + '__Foo').rules('add', { required: true, messages: { required: 'The Foo field is required'} });
            $('#Fields_' + i + '__Bar').rules('add', { required: true, messages: { required: 'The Bar field is required'} });
        }

I hope I helped you on your way !

Ps, use FireBug to help you find the correct names of the properties and that's how you can link them with the ModelErrors in the modelstate etc.