1

I am trying to validate my form in angular using reactive form .There is few fields example card name in which user enter only string

so he try to enter anything other than string I need to show invalid message .I tried like this

https://codesandbox.io/s/jzq6nn6zz9

constructor(private fb: FormBuilder) {
    this.paymentForm = this.fb.group({
      cardname: [
        "",
        [(Validators.required, Validators.pattern("[a-zA-Z][a-zA-Z ]+"))]
      ],
      cardnumber: [""],
      dateofexipiredate: [""],
      dateofexipireyear: [""],
      cvc: [""]
    });
  }

when I run my application my form is already valid why ? enter image description here it should only valid when user enter string

user5711656
  • 3,310
  • 4
  • 33
  • 70
  • 2
    Instead of waiting for an answer (it's gonna be a long one so not many people want to spend time writing something that is already explained in detail in Angular guide), read up https://angular.io/guide/reactive-forms – codeepic Jul 20 '18 at 08:57

4 Answers4

1

Remove extra brackets () in form Validators array. Validators should be sent as an array. After adding (), they are being treated as one single item, which is giving false results.

this.paymentForm = this.fb.group({
      cardname: [
        "",
        [Validators.required, Validators.pattern("[a-zA-Z][a-zA-Z ]+")] // see this line
      ],

Stackblitz

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98
1

Write 1 custom Validator for this task. I have added 1 sample here, just change your condition in the validator.

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

export function SameEmail(control: AbstractControl) {
    let email = window.localStorage.getItem("user");
    if (control.value == email) {
        return { validEmail : true };
    } else {
        return null;
    }
   
}


this.customForm = this.formBuilder.group({
        'email': new FormControl(this.customForm.email, [
          Validators.required,
          SameEmail
        ])
      });
<div *ngIf="form.email.invalid && (form.email.dirty || form.email.touched)" class="alert alert-danger">
              <div *ngIf="form.email.errors.required">
                Error 1
              </div>
              <div *ngIf="form.email.errors.validEmail">
                Error 2
              </div>
            </div>
Tarun Khurana
  • 887
  • 8
  • 9
0

Just add Validators.minLength(1) sure he enter at least one character and Validators.pattern("[a-zA-Z][a-zA-Z ]+") will check if he enter valid name

constructor(private fb: FormBuilder) {
    this.paymentForm = this.fb.group({
      cardname: [
        "",
        [Validators.required, Validators.pattern("[a-zA-Z][a-zA-Z ]+"),Validators.minLength(1)]
      ],
      cardnumber: [""],
      dateofexipiredate: [""],
      dateofexipireyear: [""],
      cvc: [""]
    });
  }
Muhammed Albarmavi
  • 23,240
  • 8
  • 66
  • 91
0

You can use formGroup error checking to make sure it works properly. yourForm.get('cardname').hasError('required') You can also check add some extra div in your HTML that will be displayed when user is doing something wrong in real time. Here's example with checking if element is required:

<div *ngIf="yourFormGrup.get('cardname').hasError('required')">Card name is required.</div>

It will be visible only when your form group contains specified error. Here's some extra reading for you that should help You out.

Macryo
  • 188
  • 2
  • 12