how can I check that the required input field is not empty, formControl cannot read the object...
public discountParamsForm = new FormGroup({
name: new FormControl('', Validators.required),
type: new FormControl('', Validators.required),
status: new FormControl('', Validators.required),
value: new FormControl('', [Validators.required, Validators.pattern(/^([0-9]{1,2}){1}(\.[0-9]{1,2})?$/),
Validators.min(1), Validators.max(100)]),
dateInput: new FormControl('', Validators.required),
categorySelect: new FormControl('', Validators.required)
});
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
<input formControlName="dateInput" fullWidth type="text" [(ngModel)]="dateRange"
nbInput placeholder="{{pickDateUI}}" [nbDatepicker]="datepicker">
<nb-rangepicker (rangeChange)="onDateChange($event)" format="yyyy-MM-dd" #datepicker></nb-rangepicker>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
console.log for value and discountparamsform
CodePudding user response:
never, never use in the same tag [(ngModel)]
and formControlName
Well, use a custom Validator.
discountParamsForm = new FormGroup({
...
dateInput: new FormControl('', this.validatorRange()),
})
validatorRange(){
return (control:AbstractControl)=>{
if (!control.value.start)
return {error:'start date is mandatory'}
if (!control.value.end)
return {error:'end date is mandatory'}
}
}
See that the control is always an object with properties "start" and "end" -so always has value, so in the custom validator we check if this properties has value or not-
CodePudding user response:
A couple things here, you are looking at the form object itself. You can see on the image of the console, the entire form is INVALID
.
If you want to see if one field in a form you can use the get method.
in your component
this.discountParamsForm.get('name');
this returns a FormControl object, and has values such as valid/invalid and many other use full indicators.
you can add a getter method in your component to check this in your html.
get name() {
return this.discountParamsForm.get('name');
}
<input [ngClass]="{'my-invalid-class': name.invalid}"
since we have a getter method we dont need to check the form directly and we can easily access the control inside the parent form.