Dynamic form validation in angular using eval

后端 未结 1 1008
难免孤独
难免孤独 2021-02-11 11:02

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 co

相关标签:
1条回答
  • 2021-02-11 11:43

    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
    })
    
    0 讨论(0)
提交回复
热议问题