输入的角度最小和最大验证器[type ='number']

时间:2017-10-16 16:54:08

标签: angular

根据我的理解(可能不太好,因为我今天才开始查看)there is are validators built in to Angular会检查<input type='number'>的最大值和最小值。
我试图在我正在构建的应用程序中使用它,但只有在输入完全为空时才会出现无效。其他值验证,甚至是我的最小/最大范围之外的数字。

I tried to replicate it in a plunk but here it is just always valid。我已经结束了漫长的一天 - 任何人都可以解释我必须做些什么来使我的插件中的字段为 有效 ,值为5-10超出此范围时 无效 ,为空或只是......无效。

4 个答案:

答案 0 :(得分:2)

我强烈建议您改用 Reactive Forms 借助反应式表单,您的业务逻辑将保留在component.ts代码中,从而使您的模板更清晰,更易于推理。

WorkingExample (based on your original plunk)

说明:

  

component.ts

myForm = new FormGroup({}) // Instantiating our form

constructor(private fb: FormBuilder){ // Injecting the ReactiveForms FormBuilder.
  this.myForm = fb.group({
    // Adding the "myNum" input to our FormGroup along with its min-max Validators.
    'myNum': ['', [Validators.min(5), Validators.max(10)]] 
  })
}
  

component.html - template

<form [formGroup]="myForm"> <!-- Binding myForm to the form in the template -->

  <label for="myNum">Some Val</label>
  <!-- formControlName binds our myNum field declared in the ts code. -->
  <input type='number' id="myNum" formControlName="myNum">

</form>

答案 1 :(得分:2)

正如文档linked in your question所述:

  

max()仅作为函数存在,而不是作为指令

two评论中引用的issues @DeborahK引起的。 但是,如果您真的想使用模板驱动的表单,您可以将这些directives放回原位:

import { Directive, Input } from '@angular/core';
import { NG_VALIDATORS, Validator, Validators, AbstractControl } from '@angular/forms';

@Directive({
  selector: 'input[max]',
  providers: [{provide: NG_VALIDATORS, useExisting: MaxValidator, multi: true}]
})
export class MaxValidator implements Validator {
  @Input() max:number;
  validate(control: AbstractControl): {[key: string]: any} {
    if(typeof this.max == 'string') this.max = +this.max;
    return this.max ? Validators.max(this.max)(control) : null;
  }
}

我允许你重构它以获得MinValidator一个!

答案 2 :(得分:0)

我在这里有一个自定义号码范围验证器:https://github.com/DeborahK/MovieHunter/tree/master/src/app/shared

它基本上是这样的:

static range(min: number, max: number): ValidatorFn {
    return (c: AbstractControl): { [key: string]: boolean } | null => {
        if (c.value && (isNaN(c.value) || c.value < min || c.value > max)) {
            return { 'range': true };
        }
        return null;
    };
}

答案 3 :(得分:0)

@Mihailo的回答是正确的,但就我而言,我正在使用

 'myNum': ['', [Validators.min(5), Validators.max(10)]] 

代替

min

通知minLengthmax不同,并且maxLengthcalc_data_avg不同。

相关问题