I am having this error and I wonder if I am doing something wrong here or it is the component not working. I am working in typescript, angular 17.
In my Formgroup I am specifying this:
limitsForm = new FormGroup({inputLimit: new FormControl('', [Validators.pattern('[0-9]+')])});
Then if I leave the field empty, my form group is valid according to 'this.limitsForm.valid'. I explicitly have to add 'Validators.required' and then the form is invalid when you leave the input empty. But I think the regex '[0-9]+' indicates one or more numbers, so it should fail without the required validator. Now I am patching it like:
limitsForm = new FormGroup({inputLimit: new FormControl('', [Validators.pattern('[0-9]+'), Validators.required])});
But I think the 'Validators.required' should not be necessary! Is this wrong working of the angular component? Or is my understanding of regex not correct?
This looks strange at first but works as intended. If the input is empty, the pattern validation is skipped. Here are a few reasons why it makes sense:
null
as a value. In this case pattern validation would behave strange. Either the value would need to be transformed to empty string before validation, which feels wrong. Or worse, the value is being coerced to 'null'
by JavaScript, which actually would can happen when the value is passed to the RegExp.test()
function, and can lead to completely unexpected results. Angular works around this issue by checking if the value is falsy, and skips validation in this case. See the source code.Validators.required
. Otherwise you would need to read and understand every single pattern used.Validators.required
validator is added to the form control. With your regex, the asterisk would need to be added manually.I would suggest you to re-write your regex to allow empty values, and add the required validator, in order to avoid any confusion:
limitsForm = new FormGroup({
inputLimit: new FormControl('', [
Validators.pattern('[0-9]*'),
Validators.required,
]),
});