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?
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.
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 }
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.
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"
Use AbstractControl#getError()
:
<div
class="ui pointing orange basic label"
*ngIf="form.getError('validateSomething', 'workDate') as error>
{{ error }}
</div>
DEMO
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With