ValidateEqual Directive for Password Confirmation

nativescriptrocks
nativescriptcore
ios

#1

I found an online solution to implement a web version of validateEqual using angular2 such that you can use it like:

login.html
<input #password=“ngModel” … />
<input #confirmPassword=“ngModel” validateEqual=“password” … />

validateEqual.directive.ts
import { Attribute, Directive } from ‘@angular/core’;
import { AbstractControl, Validator, NG_VALIDATORS } from ‘@angular/forms’;

@Directive({
// tslint:disable-next-line:directive-selector
selector: ‘[validateEqual][formControlName],[validateEqual][formControl],[validateEqual][ngModel]’,
providers: [{
provide: NG_VALIDATORS,
useExisting: ValidateEqualDirective,
multi: true
}]
})

export class ValidateEqualDirective implements Validator {

constructor(@Attribute('validateEqual') public validateEqual: string) { }

validate(abstractControl: AbstractControl): { [key: string]: any } | null {
    // Actual value (e.g.) confirm password
    const controlValue = abstractControl.value;

    // Expectued value (e.g.) password
    const expectedValue = abstractControl.root.get(this.validateEqual);
    // let expectedValue = abstractControl.parent.get(this.validateEqual);

    // Expected value != Control Value
    if (expectedValue && controlValue !== expectedValue.value) {
        // Set and Show Errors
        abstractControl.setErrors({ validateEqual: true });
        return { validateEqual: true };
    }
    return null;
}

}

If the confirmPassword != password field, it’ll throw an error right below the confirmPassword field.

This same directive broke in nativescript. Can I do something similar in nativescript? I looked into various code and examples, but I am still stuck.

Any help is appreciated. Thanks.


#2

Since nobody replied, I had to spend another 1/2 day to figure it out. The issue is that you must have your declarations of your component, custom directive and as well as the NativeScriptFormsModule in the same file.

app.routing.ts

@NgModule({
declarations: [ …, YourComponent, ValidateEqualDirective, … ],
imports: [ …, NativeScriptFormsModule, …],

})