0

I'm try to make custom Validators that give user message when he/she leave a space on text but i received this error.

  • 1-Cannot read property 'removeSpaceFromUserName' of undefined
  • 2-Cannot read property 'required' of null at Object.eval [as updateDirectives]

Here's the html of the component

    <form [formGroup]='form'>
        <div class="form-group">
            <label for="username">Username</label>
            <input 
                formControlName='username'
                id="username" 
                type="text" 
                class="form-control">
                <div *ngIf="username.touched && username.touched"  class="alert alert-danger">
                     <div *ngIf="username.errors.required"> You need to enter user name</div>
                     <div *ngIf="username.errors.minlength"> Min Length is 
                        {{ username.errors.minLength.requiredLength}}
                        </div>
                      <div *ngIf="UserNameValiditors.removeSpaceFromUserName">
                           removeSpaceFromUserName </div>   
                </div>
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input 
                formControlName='password'
                id="password" 
                type="text" 
                class="form-control">
        </div>
        <button class="btn btn-primary" type="submit">Sign Up</button>
    </form>

Here's the custom validator class

import { AbstractControl, ValidationErrors } from "@angular/forms";

export class UserNameValiditors {
    static removeSpaceFromUserName(control: AbstractControl): ValidationErrors | null {
        if ((control.value as string).indexOf(' ') >= 0) {
            return {
                removeSpaceFromUserName: true
            };
        }
        else {
            return null;
        }
    }
}

import { Component } from '@angular/core';
import { FormControl , FormGroup , Validators } from "@angular/forms";
import { UserNameValiditors } from './UserNameValditors';

@Component({
  selector: 'signup-form',
  templateUrl: './signup-form.component.html',
  styleUrls: ['./signup-form.component.css']
})
export class SignupFormComponent {

  form= new FormGroup(
    {
       username  : new FormControl('',
      [
        Validators.required,
        Validators.minLength(3) ,
        UserNameValiditors.removeSpaceFromUserName
      ]) ,
       password  : new FormControl('',Validators.required)
    });

    get username()
    {
      return this.form.get('username');
    }
  
}

0

2 Answers 2

1

You can try with this solution.

I have create a demo on Stackblitz

app.component.ts

myForms: FormGroup;

  constructor(fb: FormBuilder) {

    this.myForms = fb.group({
      username: [null, Validators.compose([
        Validators.required, Validators.minLength(3), usernameValidator])],
      password: [null, [
        Validators.required]]
    });
  }

app.component.html

<form [formGroup]="myForms">

    <label>User Name : 
        <input type="text"  formControlName="username">
    </label><br>

    <div class="errors" *ngIf="myForms.get('username').invalid && (myForms.get('username').touched || myForms.get('username').dirty)">

        <div *ngIf="myForms.get('username').hasError('required')">
            username is required
        </div>

        <div *ngIf="myForms.get('username').errors.minlength">
            username must be at least 3 characters
        </div>

        <div class="error-text" *ngIf="myForms.get('username').hasError('removeSpaceFromUserName')">
            removeSpaceFromUserName  
        </div>
    </div>

  <div class="form-group">
            <label for="password">Password</label>
            <input 
                formControlName='password'
                id="password" 
                type="text" 
                class="form-control">
        </div>
        <button class="btn btn-primary" type="submit">Sign Up</button>
</form>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your efforts , its worked. Please can you explain why required need initial value ?
1

Use hasError() to check if certain error is present on the form.

html code

<div *ngIf="username.hasError('required')"> You need to enter user name</div>
            <div *ngIf="username.hasError('minlength')"> Min Length is {{ username.hasError('minLength')}}
            </div>f
            <div *ngIf="username.hasError('removeSpaceFromUserName')">
                removeSpaceFromUserName </div>
</div>

Your working code is here

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.