为什么角度表单自定义验证不起作用?[已解决]

问题描述 投票:0回答:2

**大家好 我有 Angular 项目,对于其中的注册表,我创建了一个用于密码,另一个用于确认密码,我收到了两个错误

第一个:**

ERROR TypeError: Cannot read properties of undefined (reading 'registerForm') at confirmationPass (registration.component.ts:53:19)

第二个:

main.ts:8 ERROR Error: NG01052: formGroup expects a FormGroup instance. Please pass one in.

      Example:

      
  <div [formGroup]="myGroup">
    <input formControlName="firstName">
  </div>

  In your class:

  this.myGroup = new FormGroup({
      firstName: new FormControl()
  });
    at missingFormException (forms.mjs:1436:12)

我的注册.ts:

import { Component, ContentChild, OnInit } from '@angular/core';
import { ReactiveFormsModule,FormControl, FormGroup, Validators } from '@angular/forms';
import { faEye, faEyeSlash, faArrowRightToBracket,faCloudUpload} from '@fortawesome/free-solid-svg-icons';

@Component({
  selector: 'app-registration',
  templateUrl: './registration.component.html',
  styleUrls: ['./registration.component.css']
})
export class RegistrationComponent implements OnInit{
  registerForm:FormGroup;
  showPassword : boolean= false;
  showPasswordCon: boolean = false;
  iconof=faEye;
  iconshow=faEyeSlash;
  iconlogin=faArrowRightToBracket
  iconUpload=faCloudUpload;
  @ContentChild("inInput") input:any;

  constructor(){}
  ngOnInit(): void {
    this.registerForm= new FormGroup({
    fullName:new FormControl(null,Validators.required),
    userName:new FormControl(null,[Validators.required,Validators.pattern('^[a-z0-9_-]$')]),
    email: new FormControl(null,[Validators.required,Validators.email]),
    phoneNumber:new FormControl(null,[Validators.required]),
    password:new FormControl(null,[Validators.required,Validators.minLength(8),Validators.maxLength(15),Validators.pattern('(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}')]),
    passwordConfirmaton:new FormControl(null,[Validators.required,Validators.minLength(8),Validators.maxLength(15),this.confirmationPass]),
    dateOfBirth:new FormControl(null),
    addres:new FormControl(null),
    userImage:new FormControl(null)
    })
  }

onSubmite(){
  console.log(this.registerForm);

}
toggleShow() {
  this.showPassword= !this.showPassword;
  if (this.input) {
    this.input.type = this.showPassword ? 'text' : 'password';
  }
}
toggleShowCon() {
  this.showPasswordCon = !this.showPasswordCon;
  if (this.input) {
    this.input.type = this.showPassword ? 'text' : 'password';
  }
}
confirmationPass(){

    let pass=this.registerForm.get('password').value
    let passCon=this.registerForm.get('passwordConfirmaton').value
    if(pass !== passCon){
    return{passwordConfirmaton:true};
    }else{
       return null;
      }

}
}

这里是我的html:

<!doctype html>
<html lang="en">
    <body class="" style="
  background:linear-gradient(150deg, rgba(86,171,145,1) 0%, rgba(120,198,163,1) 50%, rgba(153,226,180,1) 67%);">
    <section class="ftco-section">
        <div class="container">
      <div class="row justify-content-start">
        <div class="col-md-6 text-start me-5">
                    <img class="heading-section " src="../assets/imgs/userlogo.png" alt="logo"><i><h3 class=" text-center">Register Form</h3></i>
                </div>
    <div class="row justify-content-start pe-5">
      <div class="col-md-6 col-lg-6">
        <div class="login-wrap p-0">
         <form [formGroup]="registerForm" (ngSubmit)="onSubmite()" action="#" class="signin-form">
          <div class="form-group">
           <label>*Full name:</label>
            <input formControlName="fullName" id="Fullname-field" type="text" class="form-control" placeholder="FullName" required>
          </div>
          <div class="form-group">
            <label>*User Name:</label>
            <input formControlName="userName" id="Username-field" type="text" class="form-control" placeholder="Unique Username" required>
          </div>
          <div class="form-group">
            <label>*Email:</label>
            <input formControlName="email" id="email-field" type="email" class="form-control" placeholder="[email protected]" required>
          </div>
          <div class="form-group">
            <label>*Phone Number:</label>
            <input formControlName="phoneNumber" id="phoneNumber" type="tel" class="form-control" placeholder="+96653*******" required>
          </div>
          <div class="form-group">
            <label>*Password:</label>
            <input formControlName="password" id="password-field" [type]="showPassword? 'text' : 'password'" class="form-control" placeholder="Password" required>
            <span class="field-icon" ><a class="type-toggle" (click)="toggleShow()">
              <fa-icon class="show-option" style=" color:#4c9781;"  [hidden]="!showPassword" [icon]="iconof"></fa-icon>
              <fa-icon class="hide-option" style=" color:#4c9781;" [hidden]="showPassword" [icon]="iconshow"></fa-icon>
           </a></span>
          </div>
          <div class="form-group">
            <label>*Password Confirmation:</label>
            <input formControlName="passwordConfirmaton" id="passwordConf-field" [type]="showPasswordCon? 'text' : 'password'" class="form-control" placeholder="Password Confirmation" required>
            <span class="field-icon" ><a class="type-toggle" (click)="toggleShowCon()">
              <fa-icon class="show-option" style=" color:#4c9781;"  [hidden]="!showPasswordCon" [icon]="iconof"></fa-icon>
              <fa-icon class="hide-option" style=" color:#4c9781;" [hidden]="showPasswordCon" [icon]="iconshow"></fa-icon>
           </a></span>
          </div>
          <div class="form-group">
            <label>*Birthday Date:</label>
            <input formControlName="dateOfBirth" id="DOB" type="date" class="form-control" placeholder="Enter Your Birthday Date" >
          </div>
          <div class="form-group">
            <label>Adress:</label>
            <input formControlName="addres" id="adress" type="text" class="form-control" placeholder="Enter Your Addres" >
          </div>
          <div class="form-group">
            <!-- <label>upload Your Image:</label>
            <input formControlName="userImage" id="userImage" type="file" class="w-25"> -->
            <label for="file-upload" class="custom-file-upload">
              <fa-icon [icon]="iconUpload" class="fa-lg"></fa-icon> upload User Image
          </label>
          <input id="file-upload" type="file"/>
          </div>

          <div class="form-group">
            <button type="submit" class="link form-control btn btn-primary submit px-3">Sign Up</button>
          </div>
          <div class="form-group d-md-flex">
            <div class=" text-md-right">
              <span class="link justify-content-center"><a routerLink="/login" style="color: #609696">Log in Here <fa-icon [icon]="iconlogin"></fa-icon></a></span>
            </div>
          </div>
        </form>
        </div>
      </div>
      </div>
        </div>
        </div>
    </section>
    </body>
</html>

**看起来我的代码是正确的,但在控制台中我有错误,我不知道我能做什么**

angular validation frontend angular-reactive-forms angular-forms
2个回答
3
投票

您尝试在验证器初始化之前访问表单

以下是如何创建验证器:

创建一个名为

form-validators.ts
的文件:

export function matchValidator(
  matchTo: string, 
  reverse?: boolean
): ValidatorFn {
  return (control: AbstractControl): 
  ValidationErrors | null => {
    if (control.parent && reverse) {
      const c = (control.parent?.controls as any)[matchTo] 
        as AbstractControl;
      if (c) {
        c.updateValueAndValidity();
      }
      return null;
    }
    return !!control.parent &&
      !!control.parent.value &&
      control.value === 
      (control.parent?.controls as any)[matchTo].value
      ? null
      : { matching: true };
  };
}

将您的表格修改为:

this.registerForm = new FormGroup({
        fullName:new FormControl(null,Validators.required),
        userName:new FormControl(null,[Validators.required,Validators.pattern('^[a-z0-9_-]$')]),
        email: new FormControl(null,[Validators.required,Validators.email]),
        phoneNumber:new FormControl(null,[Validators.required]),
        password:new FormControl(null,[Validators.required,Validators.minLength(8),Validators.maxLength(15),Validators.pattern('(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}'),matchValidator('passwordConfirmaton', true)]),
        passwordConfirmaton:new FormControl(null,[Validators.required,Validators.minLength(8),Validators.maxLength(15),matchValidator('password')]),
        dateOfBirth:new FormControl(null),
        addres:new FormControl(null),
        userImage:new FormControl(null)
    })

当然别忘了

import matchValidator from "{path}/form-validators.ts"

0
投票

我没有检查过,但我想应该是如下所示。首先,您需要创建表单,然后才能添加验证函数,因为它在自身内部使用了 this.registerForm 。

this.registerForm = new FormGroup({
   ...
   passwordConfirmaton:new FormControl(null, [Validators.required, Validators.minLength(8), Validators.maxLength(15)),
   ...
});

this.registerForm.get("passwordConfirmaton").addValidators([this.confirmationPass])
© www.soinside.com 2019 - 2024. All rights reserved.