I have an event which has start date and time, end date and time. I have used angular material date picker and NGX time-picker. I have done validation for date picker only so how I can provide validation based on the conditions.
Asked
Active
Viewed 1,968 times
1 Answers
0
if u enter data in username and click submit, date will be mandatory(validators fired). else it will be submitted.
**html code:**
<h3 class="text-center">User Details</h3>
<hr>
<form [formGroup]="form" (ngSubmit)="onSubmit($event)">
<div>
<label for="username">Username</label>
<input type="text" id="username" [ngClass]="{'form-submitted': formSubmitted}" formControlName="username" placeholder="Username"/>
</div>
<div>
<mat-form-field>
<mat-label>Choose a date</mat-label>
<input formControlName="dateValue" matInput [matDatepicker]="picker">
<mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
**ts:**
import {Component,OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators, FormArray } from '@angular/forms';
import { FormBuilder } from '@angular/forms';
import {CommonModule, NgLocalization, NgLocaleLocalization} from '@angular/common'
import { IDropdownSettings } from '../../node_modules/ng-multiselect-dropdown/';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
providers:[{ provide: NgLocalization, useClass: NgLocaleLocalization }]
})
export class AppComponent {
form: FormGroup;
formSubmitted = false;
title: any;
constructor(private formBuilder: FormBuilder) {}
buildForm() {
this.form = this.formBuilder.group({
username: [''],
dateValue:[null],
});
}
ngOnInit() {
this.buildForm();
}
onSubmit(event) {
event.preventDefault();
this.setUserValidarors();
if (this.form.valid) {
console.log(this.form.value); // Process your form
}
}
setUserValidarors(){
const datecntrl=this.form.get('dateValue');
let user=this.form.value.username;
if(user.length>0)
{
datecntrl.setValidators([Validators.required]);
}
datecntrl.updateValueAndValidity();
}
}
-
Here I perform conditional validation for date based on input text box of the username – May 15 '20 at 11:16