I've been working with Angular and grappling with the challenge of validating input fields to prevent white spaces. I decided to experiment with an IF statement, as shown below. Everything seemed to be working smoothly until I encountered an error message when a particular input field was left blank:
ERROR TypeError: formValue.employee.trim is not a function
onSubmit() { //when the user clicks the submit button
const formValue = this.telephoneForm.value;
this.submitted = true;
if (this.telephoneForm.invalid) {
const invalidControls = this._findInvalidControls();
if (invalidControls.length) {
$("[formControlName=" + invalidControls[0] + "]").focus();
}
}
if (
this.telephoneForm.invalid ||
this.alreadyExist ||
this.noEmployeesFound ||
this.noDepartmentsFound ||
this.noVendorsFound
) {
return;
}
if (
(formValue["department"] === null ||
formValue["department"].trim() === "") ||
formValue["employee"] === null ||
formValue["employee"].trim() === "" ||
formValue["vendor"] === null ||
formValue["vendor"].trim() === ""
) {
$("[formControlName='department']").focus();
$("[formControlName='employee']").focus();
$("[formControlName='vendor']").focus();
this.noEmployeesFound = true;
this.noDepartmentsFound = true;
this.noVendorsFound = true;
return false;
}
}
Check out this screenshot of the form where I implemented this code