3

In my Angular 2 and material application, I want to check whether username has already taken or not. If it is already taken then it should show the error.

I am following below guide.
https://material.angular.io/components/input/overview#error-messages

Typescript file

import {Component} from '@angular/core';
import {FormControl, Validators} from '@angular/forms';

const existingUserNames = ['rohit', 'mohit', 'ronit'];

@Component({
   selector: 'input-errors-example',
   templateUrl: 'input-errors-example.html',
   styleUrls: ['input-errors-example.css'],
})
export class InputErrorsExample {

    emailFormControl = new FormControl('', [
         Validators.required
    ]

    // I want to call below isUserNameTaken function but dont know 
    // how to use it with Validators so that error message will be visible.

    isUserNameTaken() : boolean {
       this.attributeClasses = attributeClasseses;
       this.attributeClasses.find( object => {
           if(object.attributeClass === this.attributeClass) {
               console.log("found " + JSON.stringify(object));
               return true;
           }
       });
       return false;
   }
}

HTML

 <form class="example-form">
   <md-form-field class="example-full-width">
     <input mdInput placeholder="Email [formControl]="emailFormControl">
    <md-error *ngIf="emailFormControl.hasError('required')">
      Email is <strong>required</strong>
    </md-error>

  <!-- I want to make something like that - custom validation -->

     <md-error *ngIf="emailFormControl.hasError('username-already-taken')">
        Username is already taken. Please try another.
    </md-error>
  <!-- custom validation end -->        

     </md-form-field>

2
  • Maybe take a look at this article blog.thoughtram.io/angular/2016/03/14/…? Commented Oct 11, 2017 at 20:45
  • 1
    Did you manage to get it working? If so could you share your solution please. Commented Oct 25, 2017 at 9:23

1 Answer 1

3

You just have to change your function to receive a component as parameter and return null if everything is ok and an error object if it's not. Then, put it on the component validator's array.

// Control declaration
emailFormControl = new FormControl('', [
   Validators.required, 
   isUserNameTaken
]

// Correct validator funcion
isUserNameTaken(component: Component): ValidationErrors {
    this.attributeClasses = attributeClasseses;
    this.attributeClasses.find( object => {
        if(object.attributeClass === this.attributeClass) {
            console.log("found " + JSON.stringify(object));
            // found the username
            return {
                username-already-taken: {
                    username: component.value
                }
            };
        }
    });
    // Everything is ok
    return null;
}

It's explained in more depth in the link that Will Howell put on the comments. It also explains how to do the same for non reactive forms.

Tutorial

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

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.