8

I have written a custom validator in angular 2

function validateSomething(): ValidatorFn {
  return (control: Abstractcontrol): { [key: string]: any } => {
    return {'validateSomething': 'Validation failed because'};
  }
}

Pretty simple validator. Now in the html I display a dialog based on the output of the validator. What I want is to be able to display the error from the validator ('Validation failed because'). Most tutorials that I saw use hasError('validateSomething') in the html and then hard code the error, like so:

<div class="ui pointing orange basic label" *ngIf="form.controls['workDate'].hasError('validateSomething')">
    Here I want to display the message from the validator 
</div>

Is there a way that I can get the error message from the validator?

1
  • Notice in the <div> I hard code the message to the user. What I want is to retrieve the message from the validator "Validation failed because" Commented Mar 2, 2017 at 4:22

2 Answers 2

7

Use AbstractControl#getError():

<div 
  class="ui pointing orange basic label"
  *ngIf="form.getError('validateSomething', 'workDate') as error>
  {{ error }}
</div>

DEMO

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

1 Comment

Or more cleanly form.controls.workDate.errors.validateSomething
1

Let's assume, that you have custom validation directive (appValidateSomething), which does some validation logic. 'Validate' method looks like:

validate(c: AbstractControl): { [key: string]: any; } {
    const v = c.value;
    if (isValid(v)) {
        return null;
    } else {
        // Return error object.
        return {
            'invalidValue': v
        }
    };
}

In HTML code you can write following code:

<input [(ngModel)]="model" type="text" #obj1="ngModel" appValidateSomething/>
<div *ngIf="obj1.errors && (obj1.dirty || obj1.touched)">
    <div [hidden]="!obj1.errors.invalidValue">Wrong value.</div>
</div>

It is important that 'invalidValue' from returning error-object from validate function matches with error object '.errors.invalidValue'.

1 Comment

What is the origin of obj? Is it a Form Control?

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.