0

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
  • 1
    Can't you simply create your custom validators and use those? Commented Aug 22, 2019 at 4:58

1 Answer 1

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
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.