代码之家  ›  专栏  ›  技术社区  ›  Roaa Ahmed

为什么角形自定义验证不起作用?

  •  0
  • Roaa Ahmed  · 技术社区  · 2 年前

    **大家好 我有一个有棱角的项目,里面的注册表我创建了一个用于密码,另一个用于确认密码,我有两个错误

    第一个:** 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>
    

    **我的代码似乎是正确的,在控制台中我有erorr,我不知道我能做什么**

    0 回复  |  直到 2 年前
        1
  •  3
  •   Danil Sereda    2 年前

    您试图在表单在验证器中初始化之前访问它

    以下是必须如何创建验证器:

    创建一个名为的文件 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"
    
        2
  •  0
  •   Evgeny Gurevich    2 年前

    我没有检查,但我想应该如下。首先,您需要创建表单,然后才能添加验证函数,因为它在内部使用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])