Dynamic form validation in angular using eval

萝らか妹 提交于 2021-02-06 14:20:20

问题


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.


回答1:


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

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

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


来源:https://stackoverflow.com/questions/57601703/dynamic-form-validation-in-angular-using-eval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!