I am creating Angular application including a reactive form. I also have a json schema file that should be addressed by that form, including both properties as form fields, and rules as form validation (simple and cross validation).
JSON schema: A and C required, B just required if A2
{
"$schema": "...",
"$id": "...",
...
"properties": {
"A": {
"description": "..."
"type": "string"
"enum": [
"A1",
"A2",
"A3"
]
},
"B": {
"description": "..."
"type": "string"
"enum": [
"B1",
"B2",
"B3"
]
},
"C": {
"description": "..."
"type": "string"
"enum": [
"C1",
"C2",
"C3"
]
},
},
"required": [
"A",
"C"
],
"allOf": [
{
"if": {
"properties": {
"A": {
"const": "A2"
}
}
},
"then": {
"required": [
"B"
]
}
}
]
}
Angular form.component.ts
...
myForm = new FormGroup(
{
'A': new FormControl('', Validators.required),
'B': new FormControl('', ),
'C': new FormControl('', Validators.required)
},
{
validators: [myFirstValidator]
}
);
cross-val.ts
import { ValidationErrors, ValidatorFn, FormGroup, AbstractControl } from "@angular/forms";
export const myFirstValidator: ValidatorFn =
(formGroupControl: AbstractControl): ValidationErrors | null => {
const A = formGroupControl.get('A')
const B = formGroupControl.get('B')
if ( A!.value == "A2" && B!.value === "") {
return { Brequired: true }
}
return null
};
Is there a way to create automatically the reactive form using just the json schema? At least, is there a way to create the cross validation file from the json schema?