简体   繁体   English

带有Bootstrap 4的Angular 6-表单验证电子邮件

[英]Angular 6 with bootstrap 4 - form validation e-mail

I have form to submit email , I want to add validation, so that can not be empyt(requred), can not be invalid email eg juventusSignedCr7@4.4, etc but when I add email eg neymarPleaseStopeDiving to my input and click submit no error is returned and data is submitted, only when I submit empty input i get the error message. 我有提交电子邮件的表单,我想添加验证,因此不能为empyt(requred),不能为无效的电子邮件,例如juventusSignedCr7@4.4,等等,但是当我向我的输入中添加电子邮件例如neymarPleaseStopeDiving并单击提交时,没有错误返回并提交数据,仅当我提交空输入时,我才收到错误消息。 email is required 电子邮件为必填项

Here is what i have done: 这是我所做的:

UPDATE 更新

component.ts component.ts

import { FormGroup, FormBuilder, Validators } from '@angular/forms';
...............
export class AboutComponent implements OnInit {
  angForm: FormGroup;
constructor(private flashMessages: FlashMessagesService,
    private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.angForm = this.fb.group({
      email: ['', Validators.required]
    });
  }

HTML 的HTML

    <form [formGroup]="angForm" novalidate class="form-element">
   <div class="form-group form-element_email">
              <input type="email" class="form-control" name="email" formControlName="email" #email />
            </div>
<div *ngIf="angForm.controls['email'].invalid && (angForm.controls['email'].dirty || angForm.controls['email'].touched)"
                class="alert alert-danger">
                <div *ngIf="angForm.controls['email'].errors.required">
                  Email is required.
                </div>

          <div class="form-group">
              <button (click)="addReview(email.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary form-element_btn">Book</button>
            </div>
      </form>

Question

What is wrong with my code? 我的代码有什么问题? please help newbie here though , thanks 请帮助新手,谢谢

You also can use a regular expresion for the email field, something like this, in your input tag 您还可以在输入代码中对电子邮件字段使用常规表达式,如下所示

<input type="email" class="form-control info" placeholder="Email" formControlName="email" (ngModelChange)="onChange($event)">

like this you call a function each time a user type inside, then in your Ts file, you declare the function that you put inside your input tag in your html 像这样,您每次在用户输入内容时都调用一个函数,然后在Ts文件中,将您声明的函数放在html的输入标记中

onChange(newValue) {
    const validEmailRegEx = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (validEmailRegEx.test(newValue)) {
        this.validEmail = true;
    }else {
      this.validEmail = false;
    }

  }

Just dont forget to declare the variable validEmail on the top of your file 只是不要忘记在文件顶部声明变量validEmail

validEmail:boolean = false

the constant validEmail is where you declare the regex expresion, the one that i put i really good for email validation,the method test is where you compare the expresion with the string, the method returns true or false After that in your html button tag goes something like this. 常量validEmail是您声明正则表达式表达的地方,我所说的对电子邮件验证非常有用,方法test是您将表达与字符串进行比较,该方法返回true or false之后在html button标记中这样的事情。

<button type="submit" class="btn btn-primary btn-block logBtn" [disabled]="!validEmail">ACCEDER</button>

i like this way because i can have full control of what i want in each input tag 我喜欢这种方式,因为我可以完全控制每个输入标签中的内容

Angular 6 Provides input validators like email and required. Angular 6提供输入验证程序,例如电子邮件和必填。

I generally don't want to allow me@home format and always expect a TLD (like .com, .net, .org, etc). 我通常不希望使用me@home格式,并且总是希望使用TLD(例如.com,.net,.org等)。 In addition to angular email validator I add my regex pattern to make it work. 除了有角度的email验证程序外,我还添加了正则表达式pattern以使其正常工作。

<input type="email" name="email" #emailField="ngModel" pattern="^\S*[@]\S*[.]\S*$" email required />

<div class="help-block m-1" *ngIf="!emailField.valid && (emailField.touched || emailField.dirty)">
  <small>Invalid Email</small>
</div>

email will implement Angular's default email validator. email将实现Angular的默认电子邮件验证器。

required will make this field as mandatory. required将使此字段为必填字段。

pattern="^\\S*[@]\\S*[.]\\S*$" will make sure that there is a @ and a . pattern="^\\S*[@]\\S*[.]\\S*$"将确保有一个@和一个。 followed by a string. 然后是一个字符串。

I see you are using FormGroup, what i did and works for me is add a validation when i create the FormGroup in the controller 我看到您正在使用FormGroup,我所做的和对我有用的工作是在控制器中创建FormGroup时添加一个验证

FormGroup({
  email: new FormControl('', [Validators.required, Validators.email])
})

this validator is binded to the [formGroup]="angForm" 此验证器绑定到[formGroup]="angForm"

You can also create a custom validator 您还可以创建自定义验证器

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

export function ValidateUrl(control: AbstractControl) {
  if (!control.value.startsWith('https') || !control.value.includes('.io')) {
    return { validUrl: true };
  }
  return null;
}

   /**
   a easy validator for an email could be something like this
    let a = "adas@sdfs.com"
    let b = a.split('@')
    if(b.length == 2){
      //ok
      let c = b[1].split('.')
      if(c.length >= 1){
        //ok
        //a have <something>@<something>.<something>
      }
    }
   **/

and import the validator in your controller 并将验证器导入控制器

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import { ValidateUrl } from './validators/url.validator';

@Component({
  // ...
})
export class AppComponent implements OnInit {
  myForm: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit() {
    this.myForm = this.fb.group({
      userName: ['', Validators.required],
      websiteUrl: ['', [Validators.required, ValidateUrl]],
    });
  }
}

got the example from here 这里得到了例子

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

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