Validation Errors Occurred Please Confirm the Fields and Submit It Again
Angular validation errors fabricated easy
Angular reactive forms are great. Dinamicity, validation and binding make me - and part of the community with me - prefer them over template driven ones. At the terminate of the day, however, either being reactive or template driven,
a form should let an application collect information from the users and provide
them feedback about information validation.
We retrieve that both strategies suffer from a poor way of showing error messages to the users. In this article, I will write about how nosotros tried to solve this problem in xtream .
Validation errors verbosity
How do nosotros testify validation errors for an input? As the bible (aka Angular documentation) suggests, we accept to write something like this
You can simplify this template by adding a getter in your component:
and the validation becomes:
This is a form containing simply 1 field with iv different validation types and we already cease upward with 20 lines of code. The template-driven situation is not very far from this besides: you accept to write a prepare of if
statements, at to the lowest degree ane for each validation that a field requires, and show the specific message.
While working on sofan, subsequently the commencement landing page in tardily august that required name, surname, email, birth date, city, and phone number plus some consensus, we started searching for a more than efficient and dynamic way to prove validation mistake messages in forms.
Requirements
In Utopia we would just ready validators while creating the FormControls
and a language specific bulletin based on the error type would announced nether the input. The message should be different per field and course, and possibly parametric, so that if we change a validator from Validators.min(4)
to Validators.min(5)
the message changes accordingly. Moreover, for some generic errors like required
we do non want to copy and paste "This field is required" everywhere. Instead, we would like to have a fallback to a general one (different per validation type) if the class specific one is not nowadays.
Doing so nosotros tin focus on validation logic within the component and only intendance almost messages in language files, avoiding to pollute the template with those horrible ngIf
clauses.
After some googling and brainstorming nosotros created a small library that covers all the requirements.
@xtream/ngx-validation-errors
The last solution is a set of components that permit united states to write a form template that appears make clean and brusk:
Let'south see how ValidationContextComponent
, FormFieldContainerComponent
and InputErrorsComponent
work to attain what we need.
InputErrorsComponent
This component accepts a set of error messages together with parameters and shows them translated using @ngx-interpret . Letters are merely translations keys like "NEW_HERO.NAME.ERRORS.MINLENGTH" and parameters are a JavaScript object enriching error info, such the states {minlength: 8, actuallength: 6}
, so we can use {{messageKey | interpret:params}}
. We will see shortly how this component is added into the DOM. Input error appears as a red text under the input; using innerValidationError
property of validationContext
you can move errors inside input in case, for example of a dark background.
ValidationContexComponent
The responsibility of this component is to query for all the inner FormFieldContainers
and set up into them the validation context passed as input. In the example above is "NEW_HERO". This let to employ error messages that are specific per form.
FormFieldContainerComponent
This component wraps the input in a container so that we can dynamically add together or remove the errors component nether it. This is the template.
Using content projection we add at the bottom of the input the InputErrorsComponent
passing error messages and parameters.
The FormFieldContainerComponent
so does the magic:
The component selects the FormControlName
in its content using @ContentChild. If the course control is invalid, dirty and touched information technology creates the list of current errors using the template
${validationContext}.${fieldName}.ERRORS.${errorType}
thus transforming field name and errors type in SCREAMING_SNAKE_CASE. The error blazon is identified using the keys in the errors object too equally the message parameters (you can direct look at builtin validators hither, only it works also using custom ones).
If the generated key is not present in the translations the message fallbacks to a configurable default validation context (such as "General") removing field name: "NEW_HERO.NAME.ERRORS.MINLENGTH" becomes "GENERAL.ERRORS.MINLENGTH" then you can keep some base errors general.
At the end if the component is able to read the native html element to which the form control is linked, it toggles too the class is-invalid
that you tin use to mark the input with a red border, for example.
Library usage
We know the way errors are shown and the base of operations validation context are opinioned. While extracting the validation components into a reusable library we exploited the forRoot
static method for configuration.
First of all install it using:
npm i @xtream/ngx-validation-errors
In your app.module.ts
add:
Now you tin use validationContext and formFieldContainer in your templates.
To customise general context and errors component use
The errorsComponent
must respect the below interface so that it can be substituted with the default one.
Retrieve to add it to the entryComponents listing otherwise it can not be instantiated dynamically using component mill.
You tin can find the whole Angular workspace with library and demo in the github repo. The showtime alpha release of the library is bachelor on the npm registry nether the name @xtream/ngx-validation-errors .
It's an ongoing work, so if you detect bugs or you recollect that something
is missing please open a event or submit a PR.
Thank you for reading this article!
Share whatsoever comment and ask whatsoever question here or make it touch through my LinkedIn contour .
Source: https://medium.com/swlh/angular-validation-errors-made-easy-3bc1a837c6e7
0 Response to "Validation Errors Occurred Please Confirm the Fields and Submit It Again"
Post a Comment