1

I wanted to learn form validation. So I created a simple registration with very basic details like First name, Last name, Email, Pass and Confirm pass. Validation is also simple with only two criteria:

  1. minLength(4)
  2. pattern('[A-Za-z]{4,15}')

I've a Submit button which is disabled initially but gets active iff all the fields are valid. My problem is that even after all the correct values my Submit button is still disabled. The code is somewhat lengthy.

register.component.ts

import { Component, OnInit } from '@angular/core';
...

@Component({
  ...
})
export class RegisterComponent implements OnInit {

  registerUserData ={
    firstName: "",
    lastName: "",
    email: "",
    password: "",
    userid: ""
  };

  form: FormGroup;

  constructor(private fb: FormBuilder) { 
    this.form  = this.fb.group({
      firstname:['', [Validators.required,Validators.minLength(4), Validators.pattern('[A-Za-z]{4,15}')]],
      lastname:['', [Validators...
    });

    this.form.controls.password.valueChanges
    .subscribe(
      x => this.form.controls.cnfpass.updateValueAndValidity()
    )
  }

  ngOnInit() {
  }

  registerUser() {
    if (!this.form.valid) return;
    this.form.markAsTouched();
    this.registerUserData.firstName=this.form.value.firstname;    
    ...
    console.log(this.registerUserData);
  }
}

HTML is even lengthier. So I've created a Stackblitz (I thought It will be more convenient for you). Here's the link: Stackblitz

Please correct my mistake.

PS: There is no error on console. Everything looks clean.

Tanzeel
  • 4,174
  • 13
  • 57
  • 110

1 Answers1

2

On line 28, you put your end bracket on bad place

password: ['', [Validators.required, Validators.minLength(4)], Validators.pattern('[A-Za-z0-9]{4,25}')],
                                                         
                                                         /\/\/\

Like this it will work well

password: ['', [Validators.required, Validators.minLength(4), Validators.pattern('[A-Za-z0-9]{4,25}')]],
Alexis
  • 1,685
  • 1
  • 12
  • 30
  • Is there anything else you want to suggest? Please let me know. – Tanzeel Aug 21 '20 at 07:35
  • I was using VSCode for this. I think it automatically added that bracket there and I didn't even notice. – Tanzeel Aug 21 '20 at 07:37
  • 1
    I have no suggestion about your usage of form, because it seems to be good for now. The only thing I would say is maybe to use ngOnInit instead of constructor to initialize your form, you got plenty of explaination of why using ngOnInit instead of constructor for this : - https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit - https://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit/45430181#45430181. But anyway your code is good so keep going :) – Alexis Aug 21 '20 at 07:43