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

标签 javascript validation angular user-input

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

相关文章:

php - Div 高度不会根据子控件自动扩展

javascript - Parsley.js 验证未触发

validation - coldfusion 中的 cfscript 电子邮件验证

angular - 使用angular-cli在angular2前端构建错误

angular - 如何限制angular app在iframe中加载

node.js - 在客户端哪里存储 JWT token 以及如何保护它?

javascript - 开始使用node,等待localhost

javascript - 图形中边缘标签的动态文本边距

javascript - js 减少只有空值的数组

validation - 使用自定义格式的日期时间验证。 '.' 分隔符出现问题