0

HTML code

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

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

I want to restrict pattern to only accepting the number and from range 1 - 3

Asif Ahmed
  • 137
  • 2
  • 6
  • 20

2 Answers2

1

you need to put regular expression like this [0-9]{1,3}, which allow only three digit if more than that it fail. and if you have this regular expression you might dont need maxlength validator as this regaurlar expression handle that case.

try it like

this.editThreshold = new FormGroup({
  threshold: new FormControl('', [Validators.required, Validators.pattern(/[0-9]{1,3}/)),
});
Pranay Rana
  • 175,020
  • 35
  • 237
  • 263
1

Use ng2-validation plugin for quickly solve this. https://github.com/yuyang041060120/ng2-validation#rangelength

npm install ng2-validation --save

in app module

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

Template form

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

Model driven

new FormControl('', CustomValidators.rangeLength([5, 9]))
Subhojit Mondal
  • 453
  • 7
  • 17