gpt4 book ai didi

javascript - Angular 2 自定义验证器 : check if the input value is an integer?

转载 作者:数据小太阳 更新时间:2023-10-29 04:38:11 25 4
gpt4 key购买 nike

在 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:

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

}

尽情享受吧!

关于javascript - Angular 2 自定义验证器 : check if the input value is an integer?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39799436/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com