简体   繁体   English

如何使用 api 以角度验证电子邮件地址?

[英]How to validate email address in angular using api?

How to validate email address in angular?.如何以角度验证电子邮件地址?。

When I submit the form and my email is like admin@g it doesn't detect it as a error .当我提交表单并且我的电子邮件类似于 admin@g 时,它不会将其检测为错误。 I am using angular with laravel API.我在 laravel API 中使用 angular。

<div class="form-group">
            <label for="email">Email</label>
            <input type="email" class="form-control" name="email" [(ngModel)]="form.email" #email="ngModel" [ngClass]="{'is-invalid': f.submitted && email.invalid}"
              required email placeholder="Enter your email address"/>
            <div *ngIf="f.submitted && email.invalid" class="invalid-feedback">
              <div *ngIf="email.errors.required">>> required</div>
              <div *ngIf="email.errors.email">>> must be a valid email address</div>
            </div>
          </div>    

As others have pointed out, your example email address (admin@g) looks correct.正如其他人指出的那样,您的示例电子邮件地址 (admin@g) 看起来是正确的。 What you want is to use an API which checks if the email address is really correct.您想要的是使用一个 API 来检查电子邮件地址是否真的正确。 You can use a service like Real Email that does in depth email address checks to test that the account is active.您可以使用Real Email等服务进行深入的电子邮件地址检查,以测试帐户是否处于活动状态。

In Angular you can create an async form validator like ..在 Angular 中,您可以创建一个异步表单验证器,例如 ..

@Injectable({ providedIn: 'root' })
export class AsyncEmailValidator implements AsyncValidator {
  private apiKey?: string; // put your api key here
  constructor(private http: HttpClient) {}

  validate(
    ctrl: AbstractControl
  ): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> {
    if (ctrl.value) {
      return this.http
        .get<{ status: string }>('https://isitarealemail.com/api/email/validate', {
          params: { email: ctrl.value },
          headers: {
            Authorization: this.apiKey ? 'Bearer ' + this.apiKey : [],
          },
        })
        .toPromise()
        .then((result) => {
          if (result.status === 'invalid') {
            return { invalid: true };
          } else if (result.status === 'unknown') {
            return { invalid: true };
          } else {
            // status is valid
            return null;
          }
        });
    } else {
      return Promise.resolve({invalid: true});
    }
  }
}

Then you can use that in your form definition.然后您可以在表单定义中使用它。

emailFormControl = new FormControl('', {
    updateOn: 'blur',
    asyncValidators: [this.emailValidator.validate.bind(this.emailValidator)],
});

Then bind to it in html然后在html中绑定到它

<input [formControl]="emailFormControl" />

For a more in depth article see angular email validation and get an api key to unlock the usage limit at Real Email有关更深入的文章,请参阅角度电子邮件验证并获取 api 密钥以解锁Real Email的使用限制

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM