Input type number “only numeric value” validation

后端 未结 5 1711
耶瑟儿~
耶瑟儿~ 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:12

    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;   
          } 
        }
    

提交回复
热议问题