angular校验输入内容是否是APNAPN位数为16位
可以使用Angular的表单校验器来校验输入内容是否是APN,并且位数为16位。以下是一个示例:
- 在组件的HTML文件中添加一个表单,并在输入框上添加校验器。
<form [formGroup]="myForm">
<input type="text" formControlName="apn" required apnValidator>
<div *ngIf="myForm.get('apn').hasError('required')">
APN is required
</div>
<div *ngIf="myForm.get('apn').hasError('invalidAPN')">
APN must be 16 characters long
</div>
</form>
- 在组件的TS文件中定义表单和校验器。
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html',
styleUrls: ['./my-component.component.css']
})
export class MyComponent {
myForm: FormGroup;
constructor() {
this.myForm = new FormGroup({
apn: new FormControl('', [Validators.required, this.apnValidator])
});
}
apnValidator(control: FormControl): { [s: string]: boolean } {
if (control.value && control.value.length === 16) {
return null;
} else {
return { invalidAPN: true };
}
}
}
-
在校验器中定义校验规则,如果输入内容为空或者不是16位,则返回错误信息。
-
在HTML文件中使用
*ngIf指令来判断表单是否有错误,如果有则显示错误信息。
通过以上步骤,就可以校验输入内容是否是APN,并且位数为16位
原文地址: https://www.cveoy.top/t/topic/frBF 著作权归作者所有。请勿转载和采集!