Search code examples
angularangular2-formscustomvalidator

Custom Validator - Pass in Parameter


I have this custom validator that checks if the categories field of my form has a value, and if it does, then if the mealTypes field is null, then sets mealTypes to be invalid. It is placed just outside of my component:

function validateMealType(findForm: AbstractControl): { [key: string]: boolean]} {
    if (findForm.get("mealCategoryChosen").value) {
        if (!findForm.get("mealTypes").value) {
            return { "invalidMealTypes": true };
        }
    }
    return null;
}

And I use it in my component to validate my components form:

ngOnInit() {
    this.findForm = this.formBuilder.group({
        categories: null,
        mealTypes: [null, Validators.required],
        mealCategoryChosen: null,
        distanceNumber: null,
        distanceUnit: 'kilometers',
        keywords: null,
    }, validateMealType);
}

And it works. Here is the plunker. Many thanks to the answerer of my last question for the plunker.

I just have one more acceptance criteria now.

I have this boolean property on the component:

private mealSelected: boolean = false;

At the moment I set mealTypes to be invalid if categories has a value and mealtypes is null.

I need to only set mealTypes to be invalid if categories has a value and mealTypes is null AND mealSelected === true. Is it possible to add a boolean parameter to the validateMealType function and pass in my component property mealSelected?? How would I do that? Could someone update my plunker to do that? I'm finding the answers on here with how to add a parameter to a custom validator quite hard to fully understand and correctly apply to my code.


Solution

  • You could create new FormControl to represent your current mealSelected

    this.findForm = new FormGroup({
      mealTypes : new FormControl(null, Validators.Required),
      categories : new FormControl(null),
      mealSelected : new FormControl(false) // <-- here is the new form control
    }, validateMealType);
    

    You do not have to associate the new FormControl to any html input, and you could update the value programmatically

    this.findForm.controls["mealSelected"].setValue(true) //programatically set the value
    

    I need to only set mealTypes to be invalid if categories has a value and mealTypes is null AND mealSelected === true.

    Here is how the custom validator would be

    if (
        findForm.controls["categories"].value &&
        !findForm.controls["mealTypes"].value &&
        findForm.controls["mealSelected"].value === true
    ) 
    {
        return {"invalidMealTypes": true}; 
    }
    

    Example Plunker