Input type number “only numeric value” validation

后端 未结 5 1723
耶瑟儿~
耶瑟儿~ 2021-02-03 17:43

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

5条回答
  •  心在旅途
    2021-02-03 17:54

    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.

提交回复
热议问题