Reputation: 8258
Our application consumes server data and displays it in reactive forms in various parts of the application (not at the same time).
We need to be able to validate the data not only in these various forms, but also at a higher level, where we can say that all data is valid regardless of user being on a form or not.
We would like to be able to use the same logic to validate the forms and the server data to not repeat ourselves.
We tried passing data to built-in validators but those validators only accept FormControls. We could most likely use custom validators and make those functions accept 'any'... but that does not seem correct..
What is the preferred/correct way in Angular of applying validators to data and not a FormControl (if even possible)?
Upvotes: 2
Views: 72
Reputation: 57919
You always can create a FormGroup, remember, a FormGroup exist independiently you has an input or not -I think it's a bit "using a sledge-hammer to crack a nut"- but anyway, I put an example
data = { email: "[email protected]", name: "" };
checkData(data:any){
const fool = new FormGroup({
email: new FormControl("", [Validators.required, Validators.email]),
name: new FormControl("", [Validators.required])
});
fool.setValue(data);
return (fool.valid)
}
But a validator is only a function that return null if no errors and an object if has error. You can make a function like a "validator" only get as argument any -not an abstractControl-
Upvotes: 1