Angular 输入校验:如何验证端口号
Angular 输入校验:如何验证端口号
使用 Angular 自带的 Validators 可以轻松验证用户输入的端口号是否符合规范。以下是一个校验输入内容是否是端口的示例:
- 在组件的 .ts 文件中,定义一个 FormGroup 并添加一个 FormControl。
import { Component } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
portForm: FormGroup;
constructor() {
this.portForm = new FormGroup({
port: new FormControl('', [Validators.required, Validators.pattern('^[0-9]{1,5}$'), Validators.min(1), Validators.max(65535)])
});
}
onSubmit() {
console.log(this.portForm.value);
}
}
在这个示例中,我们定义了一个名为 'port' 的 FormControl,并将它添加到了一个名为 'portForm' 的 FormGroup 中。我们使用 Validators.required、Validators.pattern、Validators.min 和 Validators.max 来设置校验规则。
- Validators.pattern 用于设置输入框只能输入数字,并且只能输入 1-5 位数字;
- Validators.min 和 Validators.max 用于设置输入数字的范围,即只能输入 1-65535 之间的数字。
- 在组件的 .html 文件中,使用 formGroup 和 formControlName 指令绑定表单。
<form [formGroup]="portForm" (ngSubmit)="onSubmit()">
<label for="port">Port:</label>
<input type="text" id="port" formControlName="port">
<button type="submit" [disabled]="!portForm.valid">Submit</button>
</form>
在这个示例中,我们使用 formGroup 指令将整个表单与 portForm 绑定,并使用 formControlName 指令将输入框与 FormControl 绑定。我们还设置了一个 Submit 按钮,只有当表单校验通过时才可用。
- 当用户在输入框中输入内容时,Angular 会自动进行校验。如果输入的内容不符合规则,则会显示相应的错误消息。
<div *ngIf="portForm.controls.port.errors">
<div *ngIf="portForm.controls.port.errors.required">Port is required.</div>
<div *ngIf="portForm.controls.port.errors.pattern">Port must be a number between 1 and 65535.</div>
<div *ngIf="portForm.controls.port.errors.min">Port must be a number between 1 and 65535.</div>
<div *ngIf="portForm.controls.port.errors.max">Port must be a number between 1 and 65535.</div>
</div>
在这个示例中,我们使用 *ngIf 指令来根据 FormControl 的错误状态显示相应的错误消息。如果输入的内容不符合规则,则会显示对应的错误消息。
AI 优化版
原文地址:https://www.cveoy.top/t/topic/ofWD 著作权归作者所有。请勿转载和采集!