首页 > 解决方案 > 创建单独的文件进行验证,以便我可以在不同的组件中使用它

问题描述

我很新,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

解决方案


我认为您应该阅读 Angular 中的自定义验证。您可以从那里获得想法。您可以创建通用验证函数并在需要时应用。

看看下面的样子

https://angular.io/guide/form-validation#custom-validators

https://www.positronx.io/angular-8-custom-validation-tutorial-with-examples/


推荐阅读