在Angular2项目中,我需要验证一些输入.
如何轻松检查输入值是否为整数?
如何轻松检查输入值是否为整数?
我尝试使用Number(control.value)为空字段返回0 – 不好.
或者不考虑空格的parseInt(control.value,10):
如果我有类似的东西:1 space 0,24 = 1,024它返回1 – 它通过验证器没有错误.
Lodash的功能如下:_.isInteger(control.value)或_.isNumeric(control.value)
//每次返回false – 这是预期的,因为输入值是字符串而不是数字.
组合这样的方法会产生一个带有许多if / else语句的混乱函数,即便如此,我也不确定我是否得到了所有边缘情况.我当然需要更直接的方法.有任何想法吗?
解决方法
这是我到目前为止发现的最干净的方式:
app.component.html:
- <input formControlName="myNumber">
app.component.ts:
validators.service.ts:
- function check_if_is_integer(value){
- if((parseFloat(value) == parseInt(value)) && !isNaN(value)){
- // I can have spacespacespace1 - which is 1 and validators pases but
- // spacespacespace doesn't - which is what i wanted.
- // 1space2 doesn't pass - good
- // of course,when saving data you do another parseInt.
- return true;
- } else {
- return false;
- }
- }
- @Injectable()
- export class ValidatoRSService {
- public isInteger = (control:FormControl) => {
- return check_if_is_integer(control.value) ? null : {
- notNumeric: true
- }
- }
- }
请享用!