0

How to I use md-error with a custom validator? Required works..great! but what about my custom validator?

<md-input-container>
     <input mdInput formControlName="etr" >

     <md-error *ngIf="WHAT!!!!!!!!!!!!!!!!!!!">
               ETR must be >=0 or <1
     </md-error>
     <md-error *ngIf="myForm.controls['etr'].hasError('required')">
            <strong>required</strong>
     </md-error>


 </md-input-container>

Here is my type script:

     this.myForm = fb.group({
         etr: [,[Validators.required,ModelValidators.validEtr]],

     })

I does show the error underline but how do I show the message?

I tried this but did not work:

    *ngIf="myForm.controls['etr'].hasError('validEtr')"

Below is my validator.ts file

import { FormControl } from '@angular/forms';

export class ModelValidators{

static validEtr(control: FormControl){
        var valid: any;
        valid=null;
        if (control.value>=0 && control.value<1){
            valid = true;
        }
        return valid ? null : { validLambda: true };

    }
}
2
  • please post code about ModelValidators.validEtr? Commented Jul 7, 2017 at 8:13
  • I added the validator.ts file..it works..as the form is disabled until valid input but I just cant show the error message. I get a red line though. Commented Jul 7, 2017 at 8:32

1 Answer 1

2

validLambda is the error type returned from your custom validator when validate failed.

so the solution is as below:

*ngIf="myForm.controls['etr'].hasError('validLambda')"
Sign up to request clarification or add additional context in comments.

2 Comments

It worked but what if I had multiple custom? How could I tell the difference?
@Tampa do you mean multiple custom validator on single element? you can distinct them by the error type returned from custom validators. hope I have got what you meant. :-)

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.