简体   繁体   中英

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. email is required

Here is what i have done:

UPDATE

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

    <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

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: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.

<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.

I generally don't want to allow me@home format and always expect a TLD (like .com, .net, .org, etc). In addition to angular email validator I add my regex pattern to make it work.

<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.

required will make this field as mandatory.

pattern="^\\S*[@]\\S*[.]\\S*$" will make sure that there is a @ and a . 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({
  email: new FormControl('', [Validators.required, Validators.email])
})

this validator is binded to the [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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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