在 Reactive 表单中验证电子邮件和 Phone 号码时遇到问题

Facing Problem in validation of email and Phone number in Reactive form

我正在开发 Angular 应用程序,我在验证电子邮件和 Phone 号码时遇到问题

问题

  1. 用于电子邮件验证 当我将 @ 放入错误的电子邮件中并且没有放入 .com 或 .in 示例时出现问题 -: abcd@gm ..不显示错误消息,

  2. 对于Phone号码验证,仅当Phone号码留空时才会显示错误信息,当我们输入phone number 并且它超过最大长度或最小长度然后它不显示任何错误消息。

component.ts

import { Component, OnInit } from '@angular/core';
import { ServicesService } from '../service/services.service';
import { FormGroup  , FormControl  , Validators } from '@angular/forms';
@Component({
  selector: 'app-register',
  templateUrl: './register.component.html',
  styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {

 constructor( public restapi:ServicesService) {

    this.user = new FormGroup({

      email: new FormControl('', [Validators.required,Validators.email]),
      phone: new FormControl('', [Validators.required, Validators.minLength(10)]),
      password: new FormControl('', [Validators.required, Validators.minLength(6)])
      });

   }
ngOnInit() {


  }
}

component.html

 <form class="example-form" novalidate (ngSubmit)='user_signup(user)'  [formGroup]='user'>
          <div class="row align-items-center">
            <div class="col-md-1">
              <label><img src="assets/imgs/email-icon.svg"/></label>
            </div>
            <div class="col-md-11">
              <mat-form-field class="example-full-width">
                <input matInput placeholder="Email" name='email' formControlName='email' value="" />
              </mat-form-field>
              <div style='color:#fff ;float: left ;font-size: 10px;' class="required" no-lines item-end *ngIf="( user.get('email').hasError('required') || user.get('email').hasError('email') ) && user.get('email').touched">
                <span class="error" *ngIf="user.get('email').hasError('required') && user.get('email').touched">
                  Email Required
                </span>
                <span class="error" *ngIf="user.value.email && user.get('email').hasError('email') && user.get('email').touched">
                  Invalid email!
                </span>
              </div>
            </div>
          </div>
          <div class="row align-items-center">
            <div class="col-md-1">
              <label><img src="assets/imgs/mobile-icon.svg"/></label>
            </div>
            <div class="col-md-11">

              <mat-form-field class="example-full-width" >
                <input matInput type='number' placeholder="Phone Number:"  name="phone" formControlName="phone" required/>

              </mat-form-field>

              <div style='color: rgb(248, 226, 226) ; float:left ; font-size: 10px;' class="required" item-end no-lines *ngIf="( user.get('phone').hasError('required') || user.get('phone').hasError('minlength') || user.get('phone').hasError('maxlength'))&& ( user.get('phone').touched)">

                <span class="error" *ngIf="user.get('phone').hasError('required') && user.get('phone').touched">
                    Phone number Required
                  </span>

                  <span class="error" *ngIf="user.get('phone').hasError('maxlength') && user.get('phone').touched">
                    Min 10 digit
                  </span>

                </div>


            </div>
          </div>
     
    <!--Phone otp-->
          <div class="row align-items-center"  >
            <div class="col-md-1">
              <label><img src="assets/imgs/otp-icon.svg"/></label>
            </div>
            <div class="col-md-9">
              <mat-form-field class="example-full-width">
                <input matInput placeholder="Verify phone otp:" value="" (input)='onInputTimePhone($event.target.value)' required/>
              </mat-form-field>
              <div>
                <span *ngIf='Otpvarification'> Please enter Otp </span>
               </div>
            </div>
            <div class="col-md-2">
              <a class="get_otp" mdbBtn mdbWavesEffect (click)="phoneGetOtp(user.value.phone)">Get otp</a>
            </div>
          </div>
  <!--Phone otp ends-->
          <div class="row align-items-center">
            <div class="col-md-1">
              <label><img src="assets/imgs/password-icon.svg"/></label>
            </div>
            <div class="col-md-9">
              <mat-form-field class="example-full-width">
                <input matInput type='{{type}}' placeholder="Password:" name='password' formControlName='password' value=""  />
              </mat-form-field>
              <div style='color: #fff ; float:left ; font-size: 10px;' class="required" text-center no-lines *ngIf="( user.get('password').hasError('required') || user.get('password').hasError('minlength') || user.get('password').hasError('maxlength'))&& user.get('password').touched">
                <span class="error" *ngIf="user.get('password').hasError('required') && user.get('password').touched">
                  Password is required
                </span>
                <span class="error" *ngIf="user.get('password').hasError('minlength') && user.get('password').touched">
                  Min 6 characters
                </span>
                </div>
            </div>
            <div class="col-md-2">
                    <a mdbWavesEffect *ngIf="!showPass" (click)="showPassword()"  class="showPassword">
                        <img src="assets/imgs/show.svg" >
                    </a>
                    <a mdbWavesEffect *ngIf="showPass" (click)="showPassword()" class="showPassword">
                        <img src="assets/imgs/hide.svg" >
                    </a>
            </div>

          </div>
         
          <button mdb mdbWavesEffect [disabled]="disabledAgreement" class="register_btn">Sign Up</button>
        </form>
  1. 实际上是正确的,test@test 可以是一个有效的电子邮件地址。
  2. minlength,不是minLength

试试这个方法

this.user = new FormGroup({

  email: new FormControl('', [Validators.required,Validators.email]),
  phone: new FormControl('', [Validators.required, Validators.pattern("[0-9]{0-10}")]),
  password: new FormControl('', [Validators.required, Validators.minLength(6)])
});

我已应用模式进行 phone 号码验证。

你为什么不用Validators.pattern

emailPattern = "^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$";
phoneNumber = "^(\+\d{1,3}[- ]?)?\d{10}$";
this.user = new FormGroup(
  email: new FormControl('', [Validators.required, Validators.pattern(this.emailPattern)]),
  // email: new FormControl('', [Validators.required, Validators.email]),
  phone: new FormControl('', [Validators.required, Validators.pattern(this.phoneNumber)]),
  password: new FormControl('', [Validators.required, Validators.minLength(6)])
  });

编辑: 请参阅此 link 了解更多详情

我建议在验证器中使用,因为您可以在验证器中导入它

import { AbstractControl } from '@angular/forms';


export function phonenovalid(control:AbstractControl):{[key:string]:any}|boolean{

    const pattern=/^\d{10}$/.test(control.value) ;
    return  pattern?{'phoneval':{value:control.value}}:true;

}