Closed DiegoGrandeAlagon closed 3 years ago
Hi @DiegoGrandeAlagon
that's working as expected because in the template the required
attribute is set.
<input
nxDatefield
nxInput
[nxDatepicker]="picker2"
formControlName="name"
required
/>
That is expected behavior from angular as you can mix template driven and reactive forms even though it should be avoided.
The example is specifically showing an error for required
if you want to show something else like if the input couldn't be parsed as a valid date you have to change this line:
<nx-error nxFormfieldError *ngIf="profileForm.get('name')?.errors?.required">
to
<nx-error nxFormfieldError *ngIf="profileForm.get('name')?.errors?.nxDatefieldParse">
and change the message accordingly.
Thanks for the reply @Phil147. If I wanted to control the two error messages I should add:
<nx-error nxFormfieldError *ngIf="profileForm.get('name')?.errors?.required">
<nx-error nxFormfieldError *ngIf="profileForm.get('name')?.errors?.nxDatefieldParse">
However, if we type some characters to the input, the two error messages are displayed. One solution would be to add a condition like the following, but I was just wondering if this was the desired behaviour.
<nx-error *ngIf="profileForm.get('name')?.errors?.required && profileForm.get('name')?.errors?.nxDatefieldParse">
<nx-error *ngIf="profileForm.get('name')?.errors?.required && !profileForm.get('name')?.errors?.nxDatefieldParse">
Yep that's expected. That is because as long as the user input cannot be parsed to a date the model value is null
and not what you typed in the input and null
triggers the required validator. Your solution is a good way to solve that.
Alternatively you could also just use one nx-error
element and move the logic you now have in the ngIfs
into the component code if that makes it easier to maintain.
<nx-error *ngIf="profileForm.get('name')?.errors">{{getErrorMessage()}}</nx-error>
getErrorMessage() {
// determine which message you want to show here
// e.g.
const errors = profileForm.get('name')?.errors;
if (errors.nxDatefieldParse) {
return 'This date is invalid';
} else if (errors.required) {
return 'Please provide a date';
}
return '';
}
Thanks a lot, @Phil147
⚡ Reproduction
StackBlitz link to reproduce the issue: https://stackblitz.com/edit/angular-qpsbzj?file=src/app/datefield-min-max-example.html
Steps to reproduce:
📗 Expected Behavior
Do not display the error message "This field is required!". The error generated should be "invalid", not "required".
📕 Actual Behavior
Show error message "This field is required!".
📦 Environment
Chrome