Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 retrieve error message from custom validator

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?

like image 574
Joe.b Avatar asked Mar 02 '17 04:03

Joe.b


People also ask

What must be returned from a custom validator function?

The validator function needs to return null if no errors were found in the field value, meaning that the value is valid. If any validation errors are found, the function needs to return an object of type ValidationErrors.

What is ValidatorFn in angular?

ValidatorFnlinkA function that receives a control and synchronously returns a map of validation errors if present, otherwise null. interface ValidatorFn { (control: AbstractControl<any, any>): ValidationErrors | null }

What is AbstractControl in angular?

It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. It also defines the properties that are shared between all sub-classes, like value , valid , and dirty . It shouldn't be instantiated directly.

What is dirty in angular?

When the user changes the value in the watched field, the control is marked as "dirty" When the user blurs the form control element, the control is marked as "touched"


1 Answers

Use AbstractControl#getError():

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

DEMO

like image 149
developer033 Avatar answered Oct 13 '22 23:10

developer033