在MVC动态字段的验证 [英] Validation of dynamic fields in a MVC

查看:144
本文介绍了在MVC动态字段的验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型看起来像

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).

MVC中的标准审定基于DataAnnotations,但我想验证(客户端和服务器端)动态地根据现场的元数据形式是动态的,可配置的。

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.

这可能吗?任何指针?

PS。我搜索了类似的问题,但没能找到一个坚实的答案。

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

推荐答案

我也有类似的情况,这是我如何处理它:

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

服务器端

在开机自检发生我遍历所有字段的值,并根据验证规则我对我的对象做了验证。然后,你可以简单地添加到ModelErrors Field对象。

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.

既然你把模板对象来查看您可以通过名称访问域字段[X] .SomeProperty 。请确保您有一个 ValidationMessageFor SomeProperty

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.);

客户端

请确保您的形式有一个ID,因此您可以访问验证()方法。
然后,你遍历所有的领域,只是添加验证请你。

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.

对于所有的验证规则检查验证jQuery的文档。

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,使用Firebug帮助您找到属性的正确名称,这就是你怎么可以在ModelState中等方面的ModelErrors它们连接。

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.

这篇关于在MVC动态字段的验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆