限制1-3范围内的数字输入值

时间:2018-03-21 06:00:26

标签: angular typescript

HTML代码

<div class="col-sm-12">
  <input class="form-control form-control-md" [ngModel]="item.threshold" placeholder="Set Threshold" formControlName="threshold"
    type="text">   
  <span class="text-danger text-small block" *ngIf="editThreshold.get('threshold').hasError('required') && editThreshold.get('threshold').touched">threshold is required.</span>
  <span class="text-danger text-small block" *ngIf="editThreshold.get('threshold').hasError('pattern') && editThreshold.get('threshold').touched">threshold value should be number.</span>
  <span class="text-danger text-small block" *ngIf="editThreshold.get('threshold').hasError('maxlength') && editThreshold.get('threshold').touched">maximum three digits.</span>                
</div>

ts代码

this.editThreshold = new FormGroup({
  threshold: new FormControl('', [Validators.required, Validators.pattern(/[0-9]/),Validators.maxLength(3)]),
});

我想将模式限制为只接受数字,范围为1 - 3

2 个答案:

答案 0 :(得分:1)

你需要像这样[0-9]{1,3}放置正则表达式,如果失败的话,只允许三位数。如果你有这个正则表达式,你可能不需要maxlength验证器,因为这个regaurlar表达式处理这种情况。

尝试像

this.editThreshold = new FormGroup({
  threshold: new FormControl('', [Validators.required, Validators.pattern(/[0-9]{1,3}/)),
});

答案 1 :(得分:1)

使用ng2-validation插件快速解决此问题。 https://github.com/yuyang041060120/ng2-validation#rangelength

npm install ng2-validation --save
在app模块中

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { CustomFormsModule } from 'ng2-validation'

import { AppComponent } from './app.component';

@NgModule({
    imports: [BrowserModule, FormsModule, CustomFormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule {
}

模板表单

<input type="text" [(ngModel)]="model.field" name="field" #field="ngModel" [rangeLength]="[5, 9]"/>
<p *ngIf="field.errors?.rangeLength">error message</p>

模型驱动

new FormControl('', CustomValidators.rangeLength([5, 9]))