0
votes

Part of my current Angular 4.4 project requires the custom validation of some form fields. Piecing together several examples, I created a test validation directive which works well. It currently is as follows:

import ...

function validateNameNotChrisFactory(coreDataService: CoreDataService) {

    return (c: FormControl) => {

        let formControlValue = "";
        const nameToCheckFor = "Chris";
        let isValid = false;
        let errorMessage = "Must not be Chris";

        if (c != null) {
            formControlValue = c.value;

            if (c.value != null) {
                console.log("Name entered: " + formControlValue);

                if (formControlValue.indexOf(nameToCheckFor) !== -1) {

                    // The form control's value is INVALID.
                    isValid = false;

                } else {
                    isValid = true;
                };
            };
        };

        const message = {
            'validateNameNotChris': {
                'message': errorMessage
            }
        };

        // If isValid == true then return null, else return message.
        return isValid ? null : message;

    };
};

@Directive({
    selector: '[validateNameNotChris][ngModel],[validateNameNotChris][formControl]',
    providers: [
        {
            provide: NG_VALIDATORS,
            useExisting: forwardRef(() => NameNotChrisValidatorDirective),
            multi: true
        }
    ]
})
export class NameNotChrisValidatorDirective {

    validator: Function;

    constructor(coreDataService: CoreDataService) {
        this.validator = validateNameNotChrisFactory(coreDataService);
    };

    validate(c: FormControl) {
        return this.validator(c);
    };
};

What I cannot seem to figure out is how I can pass some data, or a single value, into the directive so that I can make the validation directive less specific and re-use it more. For example, how could I pass in the name to test for in my example as opposed to hard coding the test name 'Chris' into it please?

Any advice would be welcome.

1
Very helpful, thanks. - TDC

1 Answers

1
votes

Make use of input tags i:e Input() event emitters inside the directive to get the values from the template into the directive and making it generic.

This post by scotch will make matters a bit easier for you https://scotch.io/tutorials/how-to-implement-a-custom-validator-directive-confirm-password-in-angular-2