0

I am working on form in angular And there is an optional field which has from and to time and I have to make condition that I only enter the from time or to time and not both times then I should see the error message but its an optional field so I have to make a custom validator for this one and I am confused about how to make this custom validation functionality for an optional field. so if anyone can help it will be great.

this is my html form code:

<div class="form-group">
                    <div class="col-lg-12 d-inline-flex">
                        <span  id="working-hours-text" class=" text-nowrap span-width" for="workingHoursFrom" [ngClass]="{'error-line-spacing': ((workHoursFrom.dirty && workHoursFrom.touched) && !workHoursTo.dirty) || (!workHoursFrom.dirty && (workHoursTo.dirty && workHoursTo.touched))}"> Working Hours:</span>
                        <div class="w-100">
                            <div id="working-hours-errorMsg" *ngIf="((workHoursFrom.dirty && workHoursFrom.touched) && !workHoursTo.dirty) || (!workHoursFrom.dirty && (workHoursTo.dirty && workHoursTo.touched))" class="help-block text-danger w-100 text-center pr-5 body-text-1">Please enter both the From and To working hours</div>
                            <div class="d-inline-flex w-100">
                                <div class=" w-100 d-inline-flex form-control text-center m-auto" [ngClass]="{'red-border': ((workHoursFrom.dirty && workHoursFrom.touched) && !workHoursTo.dirty) || (!workHoursFrom.dirty && (workHoursTo.dirty && workHoursTo.touched))}">
                                    <input id="input-working-from" formControlName="workingHoursFrom" type="time" class=" text-center m-auto pr-2 col-6" style="border: none;">
                                    <span>-</span>
                                    <input id="input-working-to" formControlName="workingHoursTo" type="time" class=" text-center m-auto pl-2 col-6" style="border: none;">
                                  </div>
                                  <em id="working-hours-errorMsg-icon" *ngIf="((workHoursFrom.dirty && workHoursFrom.touched) && !workHoursTo.dirty) || (!workHoursFrom.dirty && (workHoursTo.dirty && workHoursTo.touched))"
                                  style="padding-left: 15px;" class="fas fa-exclamation-circle red-symbol"></em>
                            </div>
                        </div>
                    </div>
                </div>

this is my ts file:

this.form = new FormGroup({
workingHoursFrom: new FormControl('', [Validators.pattern('^(2[0-4]|[0-1][0-9]):[0-5][0-9]$')]),
      workingHoursTo: new FormControl('', [Validators.pattern('^(2[0-4]|[0-1][0-9]):[0-5][0-9]$')])
});
get workHoursFrom(){ return this.form.get('workingHoursFrom');}
  get workHoursTo(){return this.form.get('workingHoursTo');}
1
  • Hi! If I'm not wrong, you are not showing neither the part you have the 'formControlName' (the optional field), nor the code ts with the declaration of your form. It would be really good you to add it to your question, in order to get better help. Please, provide a minimal reproducible example that clearly demonstrates the issue you are facing: stackoverflow.com/help/minimal-reproducible-example Ideally, you could drop the code into a online IDE like stackblitz.com and immediately someone can get to work solving the problem without first needing to re-create it. Commented Feb 1, 2022 at 16:29

1 Answer 1

0

I haven't test it, but I guess you could achive something like you want, if you do something like this:


this.form = new FormGroup({
workingHoursFrom: new FormControl('', 
[this.myOptionalValidatorFrom(
   [Validators.pattern('^(2[0-4]|[0-1][0-9]):[0-5][0-9]$')]
)]),
workingHoursTo: new FormControl('', 
[this.myOptionalValidatorTo(
   [Validators.pattern('^(2[0-4]|[0-1][0-9]):[0-5][0-9]$')]
)]),
});

.........

myOptionalValidatorFrom(validators?: (ValidatorFn | null | undefined)[]): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
        let response = null;
        
        if (this.form?.value?.workingHoursTo != null &&  this.form?.value?.workingHoursTo !='') {
           response = control.value ? Validators.compose(validators)(control) : null;
        }       

        return response;
    };
}

myOptionalValidatorTo(validators?: (ValidatorFn | null | undefined)[]): ValidatorFn {
    return (control: AbstractControl): { [key: string]: any } => {
        let response = null;
        
        if (this.form?.value?.workingHoursFrom != null && this.form?.value?.workingHoursFrom !='') {
           response = control.value ? Validators.compose(validators)(control) : null;
        }       

        return response;
    };
}

Please, once you test if it works, tell us in the commentaries, ok?

Sign up to request clarification or add additional context in comments.

5 Comments

I will try this and let you know asap that is it working or not! Thank you so much!
This is not working! I mean it doesn't affect the output. if you can help me with another possible way it will be great.
If you could provide a minimal reproducible example in stackblitz.com, I or someone else here for sure will be able to give you better help.
I don't get this point by minimal reproducible example!! but I really need help on this one so if you can do that or is there other way I can send you more details about this problem!! Thanks in advance!
The goal is that, if you create a stackblitz with your code working (even it work "bad"), somebody can fork it and edit your code, and show it working to you. Then, if it's not exactly how you want it to work, you can litlle by little guide the mate that is helping you...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.