We are facing an issue regarding the use of Validators.required in our form.
Our requirement is to make an input text mandatory (Validators.required). The default value should be empty (''). Users must enter some text into it.
The problem we are encountering is that the Validators.required rule is being applied as soon as the page loads. This means the input text field is immediately highlighted in red and flagged as invalid upon refresh.
For example, on this link https://www.primefaces.org/primeng/#/validation, in order to invalidate the 'First Name *:' field, we have to focus on the field, type something, erase it, and then lose focus.
We are using Angular 7 and PrimeNG. When we copy and paste the source code from PrimeNG, we face the same issue. However, if we replace Validators.required with Validators.pattern('\d{4}'), everything works correctly: the user has to input something before the Validators trigger validation. The form only becomes invalid after initializing this.fb.group(...).
ngOnInit(): void {
this.myform = this.fb.group({
'minBreak': new FormControl('', Validators.required)
});
}
<div style="display: flex; width: 28em;">
<span style="margin-right: 1em;">
Min break
</span>
<input type="text" pInputText formControlName="minBreak" />
</div>
The Issue: After executing
this.myform = this.fb.group({
'minBreak': new FormControl('', Validators.required)
});
,
the form status becomes INVALID. We expect it to be VALID.
The Question: Why does our form become invalid after initialization? Is it normal for Validators to run on the default value? If so, why is it not the case in the example at this link https://www.primefaces.org/primeng/#/validation?
Stackblitz Link: https://stackblitz.com/edit/angular-pnyiy3. In the console, we can see that the form status is INVALID.
Thank you for your assistance :)
Note: For JHipster users, they include
.ng-invalid:not(form) {border-left: 5px solid red;}
in the global.scss file. Once removed, everything functions properly...