使用 eval 以角度动态验证表单 [英] Dynamic form validation in angular using eval

查看:29
本文介绍了使用 eval 以角度动态验证表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 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.

这个 link 在我的用例中不起作用,因为它们使用内置的 Angular 验证.

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 以角度动态验证表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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