Formgroup Validator only verify the first letter

332 views Asked by At

I create a formGroup with a value in my ts file: constructor:

constructor(private formBuilder: FormBuilder) { }

I created my group:

testForm: FormGroup;

And init its value:

this.testForm= this.formBuilder.group({
     name: ['', [Validators.required],
});

My validator make the job when i press on the button to send the form.

onSubmit() {
    this.submitted = true;

    if (this.testForm.invalid) {
      console.log("invalid");
      console.log(this.findInvalidControls())
      return;
    }

    alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.testForm.value));
  }

This works so I decided to add a new validator in order that my name is not null and contains only LETTER. So i add a new validator:

name: ['', [Validators.required, Validators.pattern('[A-Za-z]')]],

This dont works and tell me that my forms is invalid... So i created a new function to check the errors like that:

findInvalidControls() {
    const invalid = [];
    const controls = this.testForm.controls;
    for (const name in controls) {
      if (controls[name].errors) {
        invalid.push(name);
      }
    }
    return invalid;
  }

and i call this function in my on submit if it is invalid and i can see that my name is in the array (so it is invalid). But why ?

I see that if i write only 1 letter then the forms is valid but if i wrote more than 1 it will be invalid. Why my validator only check 1 letter ? and if i have more it is false ?

1

There are 1 answers

0
Delwyn Pinto On

Your code is working as expected. Your form shows valid only for one letter, because that's the patter you have specified.

[A-Za-z] will only check for the 1st character entered to be a letter. You will have to specify the number of characters allowed to enable what you're going for. Read up on RegExp.