angularregexvalidation

Angular regex validator allows empty value, while the regex clause should demand at least one digit


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?


Solution

  • 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:

    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,
      ]),
    });