问题
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