在 Angular2 项目中,我需要验证一些输入。
如何轻松检查输入值是否为整数?
我尝试使用Number(control.value)
返回0
对于空的字段 - 不好。
or parseInt(control.value,10)
不考虑空格:
如果我有类似的东西: 1 空间 0,24 =1 ,024
它返回 1 - 通过验证器且没有错误。
Lodash 的功能如下:_.isInteger(control.value)
or _.isNumeric(control.value)
// return false every time
- 这是预期的,因为输入值是字符串而不是数字。
组合这样的方法会创建一个带有许多 if/else 语句的混乱函数,即使这样,我也不确定我是否得到了所有的边缘情况。我绝对需要一种更直接的方法。有任何想法吗?
这是迄今为止我发现的最干净的方法:
应用程序组件.html:
<input formControlName="myNumber">
应用程序组件.ts:
export class AppComponent {
myNumber:FormControl
constructor(private _ValidatorsService: ValidatorsService){
}
this.myNumber= new FormControl('defaultValue',
[ Validators.required, this._ValidatorsService.isInteger ]);
}
验证器.service.ts:
function check_if_is_integer(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 ((parseFloat(value) == parseInt(value)) && !isNaN(value));
}
@Injectable()
export class ValidatorsService {
public isInteger = (control:FormControl) => {
// here, notice we use the ternary operator to return null when value is the integer we want.
// you are supposed to return null for the validation to pass.
return check_if_is_integer(control.value) ? null : {
notNumeric: true
}
}
}
Enjoy!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)