83

How can I validate an input of type="number" to only be valid if the value is numeric or null using only Reactive Forms (no directives)?
Only numbers [0-9] and . are allowed, no "e" or any other characters.


What I've tried so far:

Template:

<form [formGroup]="form" novalidate>
    <input type="number" formControlName="number" id="number">
</form>

Component:

export class App {
  form: FormGroup = new FormGroup({});

  constructor(
    private fb: FormBuilder,
  ) {
    this.form = fb.group({
      number: ['', [CustomValidator.numeric]]
    })
  }
}

CustomValidator:

export class CustomValidator{
  // Number only validation
  static numeric(control: AbstractControl) {
    let val = control.value;

    if (val === null || val === '') return null;

    if (!val.toString().match(/^[0-9]+(\.?[0-9]+)?$/)) return { 'invalidNumber': true };

    return null;
  }
}

Plunker

The problem is when a user enters something that is not a number ("123e" or "abc") the FormControl's value becomes null, keep in mind I don't want the field to be required so if the field really is empty null value should be valid.

Cross browser support is also important (Chrome's number input fields do not allow the user to input letters - except "e", but FireFox and Safari do).

5
  • 4
    did you ever find an acceptable answer to this? I just ran into the same issue when I decided to switch from type="text" to type="number". I don't understand why Angular changes the control's value, but doesn't do anything to validity. Seems like a bug to me. Commented Oct 1, 2018 at 16:18
  • For the exact situation described, no. Unfortunetly...
    – Mihailo
    Commented Oct 3, 2018 at 14:37
  • 1
    So I don't have my implementation for this yet, but I plan to implement a custom ControlValueAccessor to overcome this behavior. I already have a custom date control that does something similar to store an ISO compliant date string in the form's value instead of the "10/16/2018" string that is displayed in the input. I'll add my solution here once I get to the bug regarding type="number" sometime this month hopefully. Commented Oct 17, 2018 at 1:28
  • I have this problem too. AngularJS had a built-in number validator, accessible using ng-messages="number", which does not have this issue. Something is intercepting the non-numeric input and clearing it out. Commented Sep 27, 2019 at 9:21
  • The issue is described at github.com/angular/angular/issues/11644. It is referenced here: github.com/angular/angular/issues/2962 Commented Sep 27, 2019 at 9:47

10 Answers 10

136

In the HTML file, you can add ngIf for your pattern like this,

<div class="form-control-feedback" *ngIf="Mobile.errors && (Mobile.dirty || Mobile.touched)">
        <p *ngIf="Mobile.errors.pattern" class="text-danger">Number Only</p>
      </div>

In .ts file you can add the Validators pattern -"^[0-9]*$"

this.Mobile = new FormControl('', [
  Validators.required,
  Validators.pattern("^[0-9]*$"),
  Validators.minLength(8),
]);
4
  • 4
    The requirement is that the field is nullable, type of number, not using directives, if its really not empty only numbers 0-9 are allowed. Please provide a working preview of your solution, this answer is really not it.
    – Mihailo
    Commented Apr 25, 2018 at 12:12
  • <div class="form-control-feedback" *ngIf="Mobile.errors && (Mobile.dirty || Mobile.touched)"> <p *ngIf="Mobile.errors.required" class="text-danger">Number Only</p> </div> Commented May 2, 2019 at 5:50
  • @mihailo you add mobile.errors.required in *ngif so, it will not allow null value. Commented May 2, 2019 at 5:51
  • 4
    Baffled as to why this has so many upvotes. It is not answering the question fully. The original poster is using <input type="number", that intercepts any non-numeric input leaving an empty control value, meaning any 'Required' message would be shown instead. Commented Sep 27, 2019 at 9:18
2

Using directive it becomes easy and can be used throughout the application

HTML

<input type="text" placeholder="Enter value" numbersOnly>

As .keyCode() and .which() are deprecated, codes are checked using .key() Referred from

Directive:

@Directive({
   selector: "[numbersOnly]"
})

export class NumbersOnlyDirective {
  @Input() numbersOnly:boolean;

  navigationKeys: Array<string> = ['Backspace']; //Add keys as per requirement
  
  constructor(private _el: ElementRef) { }

  @HostListener('keydown', ['$event']) onKeyDown(e: KeyboardEvent) {
    
    if (
      // Allow: Delete, Backspace, Tab, Escape, Enter, etc
      this.navigationKeys.indexOf(e.key) > -1 || 
      (e.key === 'a' && e.ctrlKey === true) || // Allow: Ctrl+A
      (e.key === 'c' && e.ctrlKey === true) || // Allow: Ctrl+C
      (e.key === 'v' && e.ctrlKey === true) || // Allow: Ctrl+V
      (e.key === 'x' && e.ctrlKey === true) || // Allow: Ctrl+X
      (e.key === 'a' && e.metaKey === true) || // Cmd+A (Mac)
      (e.key === 'c' && e.metaKey === true) || // Cmd+C (Mac)
      (e.key === 'v' && e.metaKey === true) || // Cmd+V (Mac)
      (e.key === 'x' && e.metaKey === true) // Cmd+X (Mac)
    ) {
        return;  // let it happen, don't do anything
    }
    // Ensure that it is a number and stop the keypress
    if (e.key === ' ' || isNaN(Number(e.key))) {
      e.preventDefault();
    }
  }
}
2

Simplest and most effective way to do number validation is (it will restrict space and special character also)

if you dont want length restriction you can remove maxlength property

HTML

<input type="text" maxlength="3" (keypress)="validateNo($event)"/>

TS

validateNo(e): boolean {
    const charCode = e.which ? e.which : e.keyCode;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
      return false
    }
    return true
}
1

I had a similar problem, too: I wanted numbers and null on an input field that is not required. Worked through a number of different variations. I finally settled on this one, which seems to do the trick. You place a Directive, ntvFormValidity, on any form control that has native invalidity and that doesn't swizzle that invalid state into ng-invalid.

Sample use: <input type="number" formControlName="num" placeholder="0" ntvFormValidity>

Directive definition:

import { Directive, Host, Self, ElementRef, AfterViewInit } from '@angular/core';
import { FormControlName, FormControl, Validators } from '@angular/forms';

@Directive({
  selector: '[ntvFormValidity]'
})
export class NtvFormControlValidityDirective implements AfterViewInit {

  constructor(@Host() private cn: FormControlName, @Host() private el: ElementRef) { }

  /* 
  - Angular doesn't fire "change" events for invalid <input type="number">
  - We have to check the DOM object for browser native invalid state
  - Add custom validator that checks native invalidity
  */
  ngAfterViewInit() {
    var control: FormControl = this.cn.control;

    // Bridge native invalid to ng-invalid via Validators
    const ntvValidator = () => !this.el.nativeElement.validity.valid ? { error: "invalid" } : null;
    const v_fn = control.validator;

    control.setValidators(v_fn ? Validators.compose([v_fn, ntvValidator]) : ntvValidator);
    setTimeout(()=>control.updateValueAndValidity(), 0);
  }
}

The challenge was to get the ElementRef from the FormControl so that I could examine it. I know there's @ViewChild, but I didn't want to have to annotate each numeric input field with an ID and pass it to something else. So, I built a Directive which can ask for the ElementRef.

On Safari, for the HTML example above, Angular marks the form control invalid on inputs like "abc".

I think if I were to do this over, I'd probably build my own CVA for numeric input fields as that would provide even more control and make for a simple html.

Something like this:

<my-input-number formControlName="num" placeholder="0">

PS: If there's a better way to grab the FormControl for the directive, I'm guessing with Dependency Injection and providers on the declaration, please let me know so I can update my Directive (and this answer).

1
  • 1
    Underrated answer. I ended up with the same solution to this. Commented Jun 20, 2022 at 15:05
1

IMO the most robust and general way to do this is by checking if the value may be converted to number. For that add a validator:

numberValidator(control: FormControl) {
  if (isNaN(control?.value)) {
    return {
      number: true
    }
  }
  return null;
}

export class App {
  form: FormGroup = new FormGroup({});

  constructor(
    private fb: FormBuilder,
  ) {
    this.form = fb.group({
      number: ['', [numberValidator]]
    })
  }
 }

You can combine it with Validators.min and/or Validators.max to further limiting the accepted values.

0

The easiest way would be to use a library like this one and specifically you want noStrings to be true

    export class CustomValidator{   // Number only validation   
      static numeric(control: AbstractControl) {
        let val = control.value;

        const hasError = validate({val: val}, {val: {numericality: {noStrings: true}}});

        if (hasError) return null;

        return val;   
      } 
    }
3
  • 1
    How could I implement this when the FormControls value is null as soon as the input contains letters?
    – Mihailo
    Commented Jul 12, 2017 at 12:44
  • I edited the answer to give an idea of how you could do it
    – luanped
    Commented Jul 12, 2017 at 12:49
  • 2
    Yes thank you but this does not solve the core of the problem. If the input contains letters let val = control.value = null. This is a problem with how angular parses the inputs value when it's of type number. If the input was type text my validation would work perfectly.
    – Mihailo
    Commented Jul 12, 2017 at 13:14
0

Try to put a minimum input and allow only numbers from 0 to 9. This worked for me in Angular Cli

<input type="number" oninput="this.value=this.value.replace(/[^\d]/,'')"  min=0>
0

In reactive forms I create shared class src/app/shared/validation.ts according to Angular help:

import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms'

export default class Validation {
  numberValidator: ValidatorFn = (control: AbstractControl): ValidationErrors | null => {
    if (isNaN(control?.value)) {
      return {
        number: true
      }
    }
    return null;
  }
}

in ts add import to component:

import Validation from 'src/app/shared/validation'

init shared class in your component:

valid: Validation = new Validation()

and add numberValidator to FormControl:

editDeviceForm = new FormGroup({
  number: new FormControl('', [Validators.required, this.valid.numberValidator]),
})
-1

You need to use regular expressions in your custom validator. For example, here's the code that allows only 9 digits in the input fields:

function ssnValidator(control: FormControl): {[key: string]: any} {
  const value: string = control.value || '';
  const valid = value.match(/^\d{9}$/);
  return valid ? null : {ssn: true};
}

Take a look at a sample app here:

https://github.com/Farata/angular2typescript/tree/master/Angular4/form-samples/src/app/reactive-validator

5
  • Or simply test it with let regex = /\D+/; regex.exec("stringToT3est"). If it does not contain digits, it will return null. But this would not work for a decimal sign.
    – knaos
    Commented Jul 12, 2017 at 12:50
  • 1
    I've tried using a regex, but thats not the core of the problem. When the input is of type number, and the value is not a number ("123e" or "abc") the FormControl's value becomes null...
    – Mihailo
    Commented Jul 12, 2017 at 12:57
  • 2
    Ok, i understand your problem now, it's not about the logic inside the CustomValidator, but how to get the input in the first place rather than null. Would it be possible to change your input from type number to type text (or simply delete it and defaults to text) and validate it that way? The user could then type any string, but the validator can then reject it
    – luanped
    Commented Jul 12, 2017 at 13:13
  • 1
    That's how I've solved it so far but when the input is of type text i lose the browsers functionalities bound to inputs of type number. Mainly the way the input acts on mobile devices.
    – Mihailo
    Commented Jul 12, 2017 at 13:16
  • 2
    I'm afraid for this use case you'll have to keep it as text and if you want the number increment functionalities, it won't be hard to build a custom control. It is in the HTML specification such that an input text of number will return value of null for something like '2e', there is no way to access the raw value : html.spec.whatwg.org/multipage/…
    – luanped
    Commented Jul 12, 2017 at 13:30
-1

Sometimes it is just easier to try something simple like this.

validateNumber(control: FormControl): { [s: string]: boolean } {

  //revised to reflect null as an acceptable value 
  if (control.value === null) return null;

  // check to see if the control value is no a number
  if (isNaN(control.value)) {
    return { 'NaN': true };
  }

  return null; 
}

Hope this helps.

updated as per comment, You need to to call the validator like this

number: new FormControl('',[this.validateNumber.bind(this)])

The bind(this) is necessary if you are putting the validator in the component which is how I do it.

5
  • 2
    Have you tested this out? This does not validate when I use id inside the CustomValidator (in my Plunker)
    – Mihailo
    Commented Jan 16, 2018 at 15:23
  • I have it running in my code, but did not put in plunker, will try to set up example when I get a few minutes, but I did update the answer to include the template
    – Ken
    Commented Jan 16, 2018 at 20:52
  • 1
    Please keep in mind that the core of the issue is how Firefox and some others behave. If you have number input and you enter "123e" that is not a number and the value of the input is null but I consider the input valid if it's value is null. The only 100% successful way I've found is to listen to input events and check the keys + copy/paste validation.
    – Mihailo
    Commented Jan 17, 2018 at 16:36
  • if you want null to be valid then just check if (control.value === null){ return null;} to the code in that will allow for null to be ok. If this is acceptable, then I will change the code.
    – Ken
    Commented Jan 18, 2018 at 18:07
  • 2
    control.value === null will be true both if the input has 123e or is empty.
    – Mihailo
    Commented Jan 19, 2018 at 14:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.