Angular 2 Custom Validator:检查输入值是否为整数?

AIo*_*Ion 7 javascript validation user-input angular

在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语句的混乱函数,即便如此,我也不确定我是否得到了所有边缘情况.我当然需要更直接的方法.有任何想法吗?

AIo*_*Ion 6

这是我到目前为止发现的最干净的方式:

app.component.html:

<input formControlName="myNumber">
Run Code Online (Sandbox Code Playgroud)

app.component.ts:

export class AppComponent {
    myNumber:FormControl

    constructor(private _ValidatorsService: ValidatorsService){
    }

    this.myNumber= new FormControl('defaultValue',
        [ Validators.required, this._ValidatorsService.isInteger ]);
}
Run Code Online (Sandbox Code Playgroud)

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

}
Run Code Online (Sandbox Code Playgroud)

请享用!

  • `if(condition){return true; } else {return false; }?:)你不是说'返回(条件);`? (3认同)

Fra*_*rzi 5

只需创建一个自定义验证器:

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;
  };
}
Run Code Online (Sandbox Code Playgroud)

然后在您的表单中使用它:

import { integer } from '...';

form.get('yourControl').setValidators([integer()]);
Run Code Online (Sandbox Code Playgroud)

即使输入文本类型,这也能工作