在Angular2项目中,我需要验证一些输入。 如何轻松检查输入值是否为整数?
我尝试使用Number(control.value)
为空字段返回0
- 不好。
或parseInt(control.value,10)
不考虑空格:
如果我有类似的东西:1空格0,24 = 1 ,024
它返回1 - 它通过验证器而没有错误。
Lodash的功能如:_.isInteger(control.value)
或_.isNumeric(control.value)
// return false every time
- 这是预期的,因为输入值是字符串而不是数字。
组合这样的方法会产生一个带有许多if / else语句的混乱函数,即便如此,我也不确定我是否得到了所有边缘情况。我当然需要更直接的方法。有什么想法吗?
答案 0 :(得分:6)
这是我到目前为止发现的最干净的方式:
<强> app.component.html:强>
<input formControlName="myNumber">
<强> app.component.ts:强>
export class AppComponent {
myNumber:FormControl
constructor(private _ValidatorsService: ValidatorsService){
}
this.myNumber= new FormControl('defaultValue',
[ Validators.required, this._ValidatorsService.isInteger ]);
}
<强> validators.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
}
}
}
享受!
答案 1 :(得分:2)
只需创建一个自定义验证器:
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export function integer(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const error: ValidationErrors = { integer: true };
if (control.value && control.value !== `${parseInt(control.value, 10)}`) {
control.setErrors(error);
return error;
}
control.setErrors(null);
return null;
};
}
然后以您的形式使用它:
import { integer } from '...';
form.get('yourControl').setValidators([integer()]);
即使输入文字类型
,这也会有效