angular - 创建单独的文件进行验证,以便我可以在不同的组件中使用它
问题描述
我很新,angular 7
我创建了一个添加新老师的新老师,它包含不同的字段,每个字段都有验证,我有一个文件
add-teacher.component.ts
它包含添加教师的所有逻辑以及验证,但是,我想创建一个不同的文件进行验证,以便将来我可以将此验证文件用于添加学生,现在我正在使用这种方式进行验证:
add-teacher.component.ts
@Component({
selector: 'app-add-teacher',
templateUrl: './add-teacher.component.html',
styleUrls: ['./add-teacher.component.css']
})
export class AddTeacherComponent implements OnInit {
teachers: Teacher[] = [];
teachersValidation = new FormGroup({
userName: new FormControl('', [
Validators.required
]),
fullName: new FormControl('',[
Validators.required
]),
branch: new FormControl('',[
Validators.required
]),
subject: new FormControl('',[
Validators.required
]),
semester: new FormControl('',[
Validators.required
]),
password: new FormControl('',[
Validators.required,
Validators.pattern("(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&].{8,}")
])
})
get validations() {
return this.teachersValidation.controls;
}
}
add-teacher.html
<div class="container">
<form>
<div class="form-group" #userform="ngForm" [formGroup]="teachersValidation">
<label for="exampleInputEmail1">user name</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
[(ngModel)]="teachers.userName" name="userName" placeholder="Enter User Name" formControlName="userName">
<div *ngIf="(validations.userName.invalid && validations.userName.touched) || validations.userName.dirty">
<small *ngIf="validations.userName.errors?.required" class="text-danger">Name is required</small>
<!--question mark(?) is a safe navigation operator-->
<small *ngIf="validations.userName.errors?.pattern" class="text-danger">Please provide a valid password</small>
</div>
</div>
<div class="form-group" #userform="ngForm" [formGroup]="teachersValidation">
<label for="exampleInputEmail1">Full Name</label>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
[(ngModel)]="teachers.fullName" name="fullName" placeholder="Enter User Name" formControlName="fullName">
<div *ngIf="(validations.fullName.invalid && validations.fullName.touched) || validations.fullName.dirty">
<small *ngIf="validations.fullName.errors?.required" class="text-danger">Full Name is required</small>
<!--question mark(?) is a safe navigation operator-->
</div>
</div>
----------------------------
所以你能不能给我一个使用相同类型验证但在不同文件中的代码,以便我可以随时调用它的方法。
谢谢。
解决方案
我认为您应该阅读 Angular 中的自定义验证。您可以从那里获得想法。您可以创建通用验证函数并在需要时应用。
看看下面的样子
https://angular.io/guide/form-validation#custom-validators
https://www.positronx.io/angular-8-custom-validation-tutorial-with-examples/
推荐阅读
- node.js - npm 错误!缺少脚本:构建:通用
- macos - Pfctl 如何为内核扩展设置防火墙规则
- php - Laravel 5 eloquent 不在数据库中存储特殊字符
- r - 在 mutate 函数中乘以选定行的总和
- spring - 从 1.5.16 升级到 Spring Boot 2 时开始出现错误 NoClassDefFoundError: ObjectMapper
- angular - TypeScript 和 chai-as-promsied:最终是无效属性
- python - 未知 URL 类型:图像抓取
- javascript - TypeError - d 未定义
- mysql - 尝试在 mysql 中运行更新查询时出现语法错误
- c# - 从外部客户端成功调用 API,但从 C# 调用失败