I have an Input field in my angular template-driven form. I want to configure that fields so that it can only take an 11bits number like 01001111100
<input
class="form-control"
id="bitsValue"
[placeholder]="field.templateOptions.placeholder"
pattern="[0-1]{1}"
[(ngModel)]="ABC"
>
How can I do that?
If you were to use reactive forms, create you form for example:
this.myForm = this._sb.fb.group(
{
bitsValue: this._sb.fb.control('', [Validators.required, YourValidatorClass.elevenBitsOnly])
};
export class YourValidatorClass {
static elevenBitsOnly(control: AbstractControl): ValidationErrors | null {
const value = control.value;
//... validate your value meets your 11 bit requirement
return { bitValueReq: 'You must provide value as 11 bits number' };
//... if it doesn't meet the requirement return null
return null;
}
}
Then in your html template:
<div [formGroup]="myForm">
<mat-form-field>
<input matInput type="text" formControlName="bitsValue" />
<mat-error *ngIf="myForm.hasError('bitValueReq'))"> {{ getErrorMessage(myForm.get('bitsValue')) }}</mat-error>
</mat-form-field>
</div>
....component.ts file:
getErrorMessage(control: AbstractControl): string{
const error = control.getError('bitValueReq');
if(error){
return error['bitValueReq'];
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.