anguar12里面自定义共通的表单check

在Angular项目中,可以通过创建一个共通的表单验证器来满足非空、长度和格式等要求,以便在每个组件的nzForm表单中重复使用。下面是一个简单的示例:

首先,在你的项目中创建一个validators.ts文件,并在其中定义一个共通的表单验证器类,如下所示:

 
  
import { AbstractControl, ValidatorFn, Validators } from '@angular/forms';

export class CustomValidators {
  static required(control: AbstractControl): { [key: string]: boolean } | null {
    return Validators.required(control);
  }

  static minLength(minLength: number): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (Validators.required(control) !== null) {
        return null;
      }

      const value = control.value as string;
      return value.length < minLength ? { 'minLength': true } : null;
    };
  }

  static pattern(pattern: string | RegExp): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (Validators.required(control) !== null) {
        return null;
      }

      const value = control.value as string;
      return new RegExp(pattern).test(value) ? null : { 'pattern': true };
    };
  }
}

接下来,在你的组件中,你可以使用这些共通的验证器来定义表单控件的验证规则。例如,假设你有一个包含一个输入框的表单组件,你可以像这样使用共通的验证器:

import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { CustomValidators } from './validators';

@Component({
  selector: 'app-my-form',
  template: `
    
Name is required
Name must be at least 3 characters long
Invalid name format
` }) export class MyFormComponent { myForm: FormGroup; constructor(private fb: FormBuilder) { this.myForm = this.fb.group({ name: ['', [CustomValidators.required, CustomValidators.minLength(3), CustomValidators.pattern(/^[A-Za-z]+$/)]] }); } submitForm() { if (this.myForm.valid) { // 执行表单提交操作 } } }

在上面的示例中,我们使用CustomValidators类中定义的共通验证器来验证输入框的值。通过在Validators数组中传递这些验证器函数,你可以将它们应用于相应的表单控件,并在模板中显示相应的错误消息。

在Angular项目中,你可以创建一个共通的表单验证服务来处理包括非空、长度、格式等基本验证和整合性验证。以下是一个示例:

import { Injectable } from '@angular/core';
import { FormGroup, AbstractControl } from '@angular/forms';

@Injectable({
  providedIn: 'root'
})
export class FormValidationService {

  constructor() { }

  // 非空验证
  required(control: AbstractControl): { [key: string]: boolean } | null {
    return control.value ? null : { 'required': true };
  }

  // 长度验证
  length(minLength: number, maxLength: number) {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value && (control.value.length < minLength || control.value.length > maxLength)) {
        return { 'length': true };
      }
      return null;
    }
  }

  // 格式验证
  pattern(regExp: RegExp) {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      if (control.value && !regExp.test(control.value)) {
        return { 'pattern': true };
      }
      return null;
    }
  }

  // 整合性验证
  validateRelations(form: FormGroup, relationList: any[]) {
    for (let relation of relationList) {
      let firstControl = form.get(relation.first);
      let secondControl = form.get(relation.second);
      if (firstControl && secondControl && firstControl.value && secondControl.value) {
        if (relation.validator(firstControl.value, secondControl.value)) {
          firstControl.setErrors({ 'relation': true });
          secondControl.setErrors({ 'relation': true });
        } else {
          firstControl.setErrors(null);
          secondControl.setErrors(null);
        }
      }
    }
  }

}

使用该服务时,你可以在组件中注入表单验证服务,并在每个表单元素中应用对应的验证器。例如:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { FormValidationService } from './form-validation.service';

@Component({
  selector: 'app-my-form',
  templateUrl: './my-form.component.html',
  styleUrls: ['./my-form.component.css']
})
export class MyFormComponent implements OnInit {

  myForm: FormGroup;

  constructor(private fb: FormBuilder, private validationService: FormValidationService) { }

  ngOnInit() {
    this.myForm = this.fb.group({
      name: ['', [this.validationService.required, this.validationService.length(2, 20)]],
      email: ['', [this.validationService.required, this.validationService.pattern(/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/)]],
      password: ['', [this.validationService.required, this.validationService.length(6, 20)]],
      confirmPassword: ['', [this.validationService.required]],
    });

    // 在失去焦点时验证表单
    for (let controlName in this.myForm.controls) {
      let control = this.myForm.controls[controlName];
      control.statusChanges.subscribe(() => {
        if (control.dirty || control.touched) {
          this.validationService.validateRelations(this.myForm, [
            { first: 'password', second: 'confirmPassword', validator: (firstValue, secondValue) => firstValue !== secondValue },
          ]);
        }
      });
    }
  }

  onSubmit() {
    this.validationService.validateRelations(this.myForm, [
      { first: 'password', second: 'confirmPassword', validator: (firstValue, secondValue) => firstValue !== secondValue },
    ]);

    if (this.myForm.valid) {
      console.log('Form submitted:', this.myForm.value);
    } else {
      console.log('Form validation failed:', this.myForm.errors);
    }
  }

}

在上述示例中,我使用了Angular的响应式表单,并创建了一个包含姓名、邮箱、密码和确认密码四个表单元素的表单。我在每个表单元素中应用了相应的验证器,如非空验证、长度验证和格式验证,并在提交表单时应用整合性验证。在失去焦点时验证表单时,我使用statusChanges方法来订阅表单元素状态的改变,并调用共通的表单验证服务中的validateRelations方法来处理整合性验证。

在Angular项目中,您可以创建一个共通的Service来处理表单验证的功能。以下是一个示例:

  1. 创建一个共通的ValidationService:
import { Injectable } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';

@Injectable({
  providedIn: 'root'
})
export class ValidationService  constructor() {  // 非空
  static required: FormControl { [key:]: boolean } | {
    if (.value === null || control.value === '') {
      return { 'required': true };
    }
    return null;
  }

  // 长度验证
  static maxLength(length: number) {
    return (control: FormControl): { [key: string]: boolean } | null => {
      if (control.value && control.value.length > length) {
        return { 'maxlength': true };
      }
      return null;
    };
  }

  // 格式验证(示例:邮箱格式)
  static emailFormat(control: FormControl): { [key: string]: boolean } | null {
    const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    if (control.value && !emailRegex.test(control.value)) {
      return { 'emailFormat': true };
    }
    return null;
  }

  // 整合性验证(示例:两个表单元素相等)
  static match(controlName: string, matchingControlName: string) {
    return (formGroup: FormGroup): { [key: string]: boolean } | null => {
      const control = formGroup.controls[controlName];
      const matchingControl = formGroup.controls[matchingControlName];

      if (matchingControl.errors && !matchingControl.errors.match) {
        return null;
      }

      if (control.value !== matchingControl.value) {
        matchingControl.setErrors({ 'match': true });
      } else {
        matchingControl.setErrors(null);
      }
      return null;
    };
  }
}
  1. 在组件中使用ValidationService:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { ValidationService } from 'path/to/validation.service';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
  styleUrls: ['./your-component.component.css']
})
export class YourComponent implements OnInit {
  form: FormGroup;

  constructor(private formBuilder: FormBuilder) { }

  ngOnInit() {
    this.form = this.formBuilder.group({
      email: ['', [ValidationService.required, ValidationService.emailFormat]],
      password: ['', [ValidationService.required, ValidationService.maxLength(10)]],
      confirmPassword: ['', [ValidationService.required]]
    }, {
      validator: ValidationService.match('password', 'confirmPassword')
    });
  }

  // 失去焦点时验证
  onBlur(controlName: string) {
    const control = this.form.get(controlName);
    if () {
      control.markAsTouched();
    }
  }

  // 提交表单时验证
  onSubmit() {
    if (this.form.valid) {
      // 表单验证通过,执行提交操作
    } else {
      // 表单验证失败,处理错误信息
    }
  }
}
  1. 在模板中使用ValidationService:
Email is required.
Invalid email format.
Password is required.
Password length exceeds the limit.
Confirm Password is required.
Passwords do not match.

在上述示例中,我们创建了一个ValidationService,其中包含了常用的验证方法。在组件中,我们使用FormGroup和FormControl来构建表单,并将ValidationService中的验证方法应用到相应的FormControl上。在模板中,我们使用formControlName指令来绑定FormControl,并使用*ngIf指令来显示验证错误信息。

失去焦点时,我们调用onBlur方法来标记FormControl为已触摸状态,以便在模板中显示相应的错误信息。提交表单时,我们调用onSubmit方法来检查表单的有效性,并执行相应的操作。

整合性验证可以通过在FormGroup中使用validator选项来实现。在上述示例中,我们使用ValidationService中的match方法来验证两个密码字段是否相等

你可能感兴趣的:(angular.js,前端,javascript)