使用eval在angular中进行动态表单验证

问题描述:

我在Angular 7中有一个动态表单,字段,控件类型,可见性,验证以及所有内容都来自数据库.我知道对于动态表单,如果来自数据库的验证是在Angular验证中构建的,则要容易得多,但是我想做的是为每个控件类型和每个控件类型的验证数组构建自定义验证.使用eval,将其评估为true/false,并根据该错误显示相应的错误消息.

I have a dynamic form in Angular 7 and the fields, control-type, visibility, validations, everything comes from the database. I know that for dynamic forms if the validations coming from the database are built in Angular validations, it is much easier to do, but what I would like to do is build a custom validation for the array of validations coming for each control-type and using eval, evaluate it to true/false and based on that show the corresponding error messages.

This link wont work in my usecase, because they are using built in Angular validations.

Remyaj,该链接显示验证器来自类似对象的

Remyaj, the link show that the validators comes from an object like

validations: [{
  name: "required",
  validator: Validators.required,
  message: "Name Required"
  }]

如果这是来自dbs,那么您的对象可以像

Well if this comes from a dbs, your object can be like

validations: [{
  name: "required",
  message: "Name Required"
  },
  {
  name:"custom",
  message: "Name Custom error"
  }]

您唯一需要做的就是制作一张地图,获取数据后,就像

The only thing that you need is make a map, when recived the data, some like

getShema().pipe(map((res:any)=>{
     res.forEach((field:any)=>{
         if (field.validations)
         {
              field.validations.forEach(validator=>{
                     switch (validator.name)
                     {
                           case "required":
                                validator.validator=Validator.required
                                break;
                           case "custom":
                                validator.validator=myCustomValidator
                                break;
                           ...
                     }
              }
         }
     }
     return res
})