Some concepts and methods of angular forms

UntypedFormGroup

UntypedFormGroup is a type-safe FormGroup, which is a form control container used to organize and manage a group of form controls

markAsPristine() Method used to mark the FormGroup in "pristine" (unmodified) state. This means that the form control's value has not been modified. This method is usually used to reset the form state after the form is submitted or when resetting the form.

updateValueAndValidity() This method is used to update the validation status of the FormGroup and all controls under it. It triggers validation rules to validate each control, and updates the control's  valid, invalid, touched and  dirty status based on the validation results.

markAsPristine() Methods and  updateValueAndValidity() methods are two common methods provided by FormGroup for managing and manipulating the state and validation of form controls.

import { FormGroup, FormControl } from '@angular/forms';

// 创建一个 FormGroup
const formGroup = new FormGroup({
  name: new FormControl(''),
  email: new FormControl('')
});

// 将 FormGroup 标记为 pristine
formGroup.markAsPristine();

// 更新 FormGroup 及其下所有控件的验证状态
formGroup.updateValueAndValidity();

2 How to implement form custom validation

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
    <div class="form-item">
        <div>
            <label for="username">用户名:</label>
            <input type="text" id="username" formControlName="username" >
        </div>
        <div *ngIf="myForm.get('username')?.invalid && myForm.get('username')?.touched" class="error">用户名不能为空</div>
    </div>
    <div  class="form-item">
        <div>
            <label for="password">密码:</label>
            <input type="password" id="password" formControlName="password" >
        </div>
        <div *ngIf="myForm.get('password')?.invalid && myForm.get('password')?.touched" class="error">
            密码必须包含英文大小写并且长度在8到12之间
        </div>
    </div>
   
    <div  class="form-item">
        <div>
            <label for="phone">手机号:</label>
            <input type="text" id="phone" formControlName="phone" >
        </div>
        <div *ngIf="myForm.get('phone')?.invalid && myForm.get('phone')?.touched" class="error">
            手机号必须是11位数字且第二个数字不能是2
        </div>
    </div>
    <div  class="form-item">
        <button type="submit">提交</button>
    </div>
  

  </form>
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators ,FormControl} from '@angular/forms';
import { Observable, of } from 'rxjs';

@Component({
  selector: 'app-formpage',
  templateUrl: './formpage.component.html',
  styleUrls: ['./formpage.component.less']
})
export class FormpageComponent {
  myForm:FormGroup;
  constructor(private fb:FormBuilder){
    this.myForm=this.fb.group({
      username:['',Validators.required],
      password:['',Validators.required,this.passwordValidator],
      phone:['',Validators.required,Validators.pattern(/^1[^2]\d{9}$/)],
    })
  }
  validateField(field:string){

    const control=this.myForm.get(field);
    console.log("control:",control)
    if(control?.invalid){
      control.markAllAsTouched()
    }
  }

  // 异步密码验证器函数
  passwordValidator(control: FormControl): Promise<{ [key: string]: boolean } | null> {
      const value = control.value;
      const valid =  value.length >= 8 && value.length <= 12;
      console.log("control.value:",control.value)
      return new Promise((resolve,reject)=>{
            if (!valid) {
              resolve({ invalidPassword: true });
            } else {
              resolve(null);
            }
      })
}
  onSubmit(){
    if(this.myForm.valid){
      console.log("this,.form.value",this.myForm.value)
    }else{
      console.log("--invaid--")
      console.log("this,.form.value",this.myForm.value)
      this.myForm.markAllAsTouched()
    }
  }
}

Note: if the verification function passes, it will return null, so the final return value of our verification function must consider the value of null. That is, passwordValidator(control: FormControl): Promise<{ [key: string]: boolean } | null>

If it does not pass when submitting, you need to call the markAllAsTouched() method on the form. This will display an error message

Guess you like

Origin blog.csdn.net/baidu_41601048/article/details/131680836