Search code examples
htmlangulartypescript

Why the form is always invalid after its submission?


signup.html :

<form [formGroup]="signupForm"  (submit)="onSubmit()" class="form-detail" >
                <h2>Registration Form</h2>
                <div class="form-row-total">
                    <div class="form-row">
                        <input type="text" name="full-name" id="full-name" class="input-text" placeholder="Your Name" required>
                    </div>
                    <div class="row" >
                          <div *ngIf="signupForm.controls.name.errors?.['required']" class="alert alert-danger" role="alert">
                            Enter a name
                          </div>
                          <div *ngIf="signupForm.controls.name.errors?.['nom'] " class="alert alert-danger" role="alert">
                            Invalid name form
                          </div>
                     </div>
                    <div class="form-row">
                        <input type="text" name="your-email" id="your-email" class="input-text" placeholder="Your Email" required pattern="[^@]+@[^@]+.[a-zA-Z]{2,6}">
                    </div>
                    <div class="row" >
                          <div *ngIf="signupForm.controls.email.errors?.['required'] " class="alert alert-danger" role="alert">
                            Enter an email
                          </div>
                          <div *ngIf="signupForm.controls.email.errors?.['email'] " class="alert alert-danger" role="alert">
                            Invalid email form
                          </div>
                          <div *ngIf="userexist" class="alert alert-danger" role="alert">
                            User already exists
                          </div>
                      </div>
                </div>
                <div class="form-row-total">
                    <div class="form-row">
                        <input type="password" name="password" id="password" class="input-text" placeholder="Your Password" required>
                    </div>
                    <div class="row" >
                          <div *ngIf="signupForm.controls.password.errors?.['required']   " class="alert alert-danger" role="alert">
                            Enter a password
                          </div>
                          <div *ngIf="signupForm.controls.password.errors?.['matchPassword']  " class="alert alert-danger" role="alert">
                            Passwords does not match
                          </div>
                          
                     </div>
                    <div class="form-row">
                        <input type="password" name="comfirm-password" id="comfirm-password" class="input-text" placeholder="Confirm Password" required>
                    </div>
                    <div class="row" >
                        <div *ngIf="signupForm.controls.password.errors?.['matchPassword']  " class="alert alert-danger" role="alert">
                          Passwords does not match
                        </div>
                        
                   </div>
                </div>
                <div class="form-row-last">
                    <input type="submit" name="register" class="register" value="Sign Up">
                </div>
            </form>

signup.ts:

async onSubmit(): Promise<void> {
    if (this.signupForm.valid) {
      const name = this.signupForm.get('name')!.value;
      const email = this.signupForm.get('email')!.value;
      const password = this.signupForm.get('password')!.value;
      const confirmpassword = this.signupForm.get('confirmpassword')!.value;
      const userExists = await this.checkIfUserExists(email);

      if (userExists) {
        this.errorMessage = 'User already exists. Please use a different email.';
        this.userexist=true;
      } else {
        this.errorMessage = null;
        this.signupForm.reset();
        await this.addNewUser(name, email, password);
        await this.registeruser(name, email, password);
        this.router.navigate(['/dashboard']); 
      }
    } else {
      console.log('Form is invalid');
    }
  }

so after filling the input fields , the msg "form is invalid" always appears in dev tools whenever i press on the button even if the formats are correct plz if u can improve my html code ( i want the alerts to appear just after pressing the button , and then they disappear after filling the fields again , or u can do whatever u want if u have a better idea )


Solution

  • In your signup-component.html correctly bind controls name, email, password, confirmPassword to the signupForm. Also When it comes to the error messages display them only when the form is submitted and the form fields are invalid state only. Refer to the following code below and refactor your code accordingly.

    sign-component.html:

    <form [formGroup]="signupForm" (ngSubmit)="onSubmit()" class="form-detail">
        <h2>Registration Form</h2>
        <div class="form-row-total">
            <div class="form-row">
                <input type="text" formControlName="name" class="input-text" placeholder="Your Name" required>
                <div *ngIf="signupForm.controls.name.touched && signupForm.controls.name.errors?.required" class="alert alert-danger" role="alert">
                    Enter a name
                </div>
            </div>
            <div class="form-row">
                <input type="text" formControlName="email" class="input-text" placeholder="Your Email" required pattern="[^@]+@[^@]+.[a-zA-Z]{2,6}">
                <div *ngIf="signupForm.controls.email.touched && signupForm.controls.email.errors?.required" class="alert alert-danger" role="alert">
                    Enter an email
                </div>
                <div *ngIf="signupForm.controls.email.touched && signupForm.controls.email.errors?.pattern" class="alert alert-danger" role="alert">
                    Invalid email format
                </div>
                <div *ngIf="userExists" class="alert alert-danger" role="alert">
                    User already exists
                </div>
            </div>
        </div>
        <div class="form-row-total">
            <div class="form-row">
                <input type="password" formControlName="password" class="input-text" placeholder="Your Password" required>
                <div *ngIf="signupForm.controls.password.touched && signupForm.controls.password.errors?.required" class="alert alert-danger" role="alert">
                    Enter a password
                </div>
            </div>
            <div class="form-row">
                <input type="password" formControlName="confirmPassword" class="input-text" placeholder="Confirm Password" required>
                <div *ngIf="signupForm.controls.confirmPassword.touched && signupForm.hasError('passwordMismatch')" class="alert alert-danger" role="alert">
                    Passwords do not match
                </div>
            </div>
        </div>
        <div class="form-row-last">
            <input type="submit" class="register" value="Sign Up">
        </div>
    </form>
    

    sign-up.component.ts:

    import { Component, OnInit } from '@angular/core';
    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    
    @Component({
        selector: 'app-signup',
        templateUrl: './signup.component.html',
        styleUrls: ['./signup.component.css']
    })
    
    
    export class SignupComponent implements OnInit {
        signupForm: FormGroup;
        userExists = false;
    
        constructor(private formBuilder: FormBuilder) {}
    
        ngOnInit(): void {
            this.signupForm = this.formBuilder.group({
                name: ['', Validators.required],
                email: ['', [Validators.required, Validators.pattern('[^@]+@[^@]+\\.[a-zA-Z]{2,6}')]],
                password: ['', Validators.required],
                confirmPassword: ['', Validators.required]
            }, { validator: this.passwordMatchValidator });
        }
    
        async onSubmit(): Promise<void> {
            if (this.signupForm.valid) {
                const name = this.signupForm.get('name').value;
                const email = this.signupForm.get('email').value;
                const password = this.signupForm.get('password').value;
    
                const userExists = await this.checkIfUserExists(email);
    
                if (userExists) {
                    this.userExists = true;
                } else {
                    this.userExists = false;
                    await this.addNewUser(name, email, password);
                    await this.registerUser(name, email, password);
                    this.signupForm.reset();            
                }
            } else {
               
                this.signupForm.markAllAsTouched();
            }
        }
    
        async checkIfUserExists(email: string): Promise<boolean> {
            return false;
        }
    
        async addNewUser(name: string, email: string, password: string): Promise<void> {
        }
    
        async registerUser(name: string, email: string, password: string): Promise<void> {
    
        }
    
        passwordMatchValidator(formGroup: FormGroup) {
            const password = formGroup.get('password').value;
            const confirmPassword = formGroup.get('confirmPassword').value;
            if (password !== confirmPassword) {
                formGroup.get('confirmPassword').setErrors({ passwordMismatch: true });
            } else {
                formGroup.get('confirmPassword').setErrors(null);
            }
        }
    }