Input type number “only numeric value” validation

后端 未结 5 1710
耶瑟儿~
耶瑟儿~ 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 18:04

    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

提交回复
热议问题