0

I have:

<input
   type="number"
   formControlName="xyz"

and I have:

    this.reportForm.addControl(
        'xyz',
        new FormControl(xyz, [Validators.pattern("^[0-9]*$")])
    );

I only want it to accept numbers. But when I enter e.g. "2dddd" the value of the form control changes to null and the state of the formcontrol stays VALID.

farahm
  • 1,326
  • 6
  • 32
  • 70
  • If you use `type="number"`, when you input the character other than numeric, it will not be allowed. Example, when entering: "2dddd", it will only accept 2. [Demo](https://stackblitz.com/edit/stackblitz-starters-ojhsvw?file=src%2Fmain.ts). So I doubt what is your actual issue? – Yong Shun Jul 08 '23 at 01:23
  • Firefox allows entering non numbers – farahm Jul 08 '23 at 09:33
  • Hmmm, can I know which Mozilla version you used? You may also refer to this [link](http://html5test.com/compare/feature/form.number.element.html) to see the browser version which support ``. – Yong Shun Jul 08 '23 at 09:43
  • 1
    In case, you may look for this [question](https://stackoverflow.com/q/41465542/8017690) to implement the input with numeric only via Angular directive. – Yong Shun Jul 08 '23 at 09:45

1 Answers1

0

From your snippets it appears that you are adding the controls dynamically, ie. at the moment the form is constructed and bound to the template, the control xyz does not exist yet. This might be the root cause. If this is the case you might have to run this.reportForm.get('xyz').updateValueAndValidity().

The "static" approach (ie. when you declare the control in the construction phase) works fine for me, ie. I am not able to type d

@Component({
  selector: 'my-app',
  standalone: true,
  imports: [CommonModule, FormsModule, ReactiveFormsModule],
  template: `
    <form [formGroup]="form">
      <input type="number" formControlName="xyz">
    </form>
  `,
})
export class App {
  form = new FormGroup({
    xyz: new FormControl('', [Validators.pattern('^[0-9]*$')]),
  });
}

Don't be surprised though that the input of type number may accept the letter e (as part of exponential notation).

user776686
  • 7,933
  • 14
  • 71
  • 124