Angular 将数字的输入值限制在1-3范围内
HTML代码Angular 将数字的输入值限制在1-3范围内,angular,typescript,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="edi
<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>
我想将模式限制为只接受数字,范围为1-3您需要像这样放置正则表达式
[0-9]{1,3}
,如果超过这个值,它只允许三位数字。如果您有这个正则表达式,您可能不需要maxlength
验证器,因为这个regaular表达式可以处理这种情况
试一试
this.editThreshold = new FormGroup({
threshold: new FormControl('', [Validators.required, Validators.pattern(/[0-9]{1,3}/)),
});
您需要像这样放置正则表达式
[0-9]{1,3}
,如果超过此值,则只允许使用三位数字。如果您有这个正则表达式,您可能不需要maxlength
验证器,因为这个regaular表达式可以处理这种情况
试一试
this.editThreshold = new FormGroup({
threshold: new FormControl('', [Validators.required, Validators.pattern(/[0-9]{1,3}/)),
});
使用ng2验证插件快速解决此问题。 应用程序内模块
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>
使用ng2验证插件快速解决此问题。 应用程序内模块
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>
你能不能请你在stack Bizy提供代码可能重复的你能不能请你在stack Bizy提供代码可能重复的