Angular Reactive form setValue setting string to number input type, input box empty but string value is assigned in controlls, validation required is not working

This is Form Controller

    ngOnInit() {
       this.profileForm = new FormGroup({
         name: new FormControl("", Validators.required),
         age: new FormControl("", Validators.required),
       }
    }

    patchAge(){
      this.profileForm.controls["age"].setValue("somethingString");
    }

This is template

<form [formGroup]="profileForm" (ngSubmit)="onFormSubmit()">
    <input
      type="text"
      formControlName="name"
    />
    <input
      type="number"
      formControlName="age"
    />
</form>
2

There are 2 best solutions below

0
On

The only validator your age control has is required, which means the value cannot be empty, so the value can be anything.

Even though you are setting the input as type=number, this is just a HTML validation, you are expecting your form object to be aware of this.

patchAge(){
  this.profileForm.get("age")?.patchValue("somethingString");
  console.log('Is my form valid?: ', this.form.valid) // TRUE
}

That's why your form valid state is TRUE, because it has indeed a value.

So the solution for this will be to add another validation to age

age: new FormControl("", [
  Validators.required, 
  Validators.pattern(/^\d+$/) // only numbers
]),

If you print right from the beginning the valid state of your form, it should be false

0
On

try to change "" to 0 as follows age: new FormControl("", Validators.required) to age: new FormControl(0, Validators.required) on ngOnInit()