使用eval在angular中进行动态表单验证 [英] Dynamic form validation in angular using eval

查看:101
本文介绍了使用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
})

这篇关于使用eval在angular中进行动态表单验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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