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

1
  • 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 angular.io/guide/reactive-forms Commented Jul 20, 2018 at 8:57

4 Answers 4

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

Sign up to request clarification or add additional context in comments.

7 Comments

hi it is correctly work but why it is invalid when I type a or when I type any charter .after tying second character it show valid
Because of your validation Validators.pattern("[a-zA-Z][a-zA-Z ]+") which requires minimum of 2 characters
If you want only one, then you may do Validators.pattern("[a-zA-Z]+")
can you please tell me one more thing how I will add pattern of 16 digit card number ..user only enter number in card number and which exact 16
Check the post stackoverflow.com/questions/9315647/… That should help you.
|
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>

Comments

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: [""]
    });
  }

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.