Angular6 - How to properly validate and don't accept empty input fields

I am working with Angular and trying to figure out how to properly validate input field and it should not accept white spaces. I tried experimenting it with IF statement like below. It seems to be working just fine but when one input field is blank I get this error message:

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;
 }
}

See this for screenshot of the form where I use this code

2 answers

  • answered 2019-01-11 05:29 Sachin Shah

    Try with this.

    formValue.employee.toString().trim()
    

  • answered 2019-01-11 06:13 Soumya B. Athani

    try this will help you

        pattern: any;
            ngOninit() {
        this.pattern = "^\S{0,50}$";
    //you can use this pattern to avoid space at beginning and end "^[^\s]+(\s+[^\s]+)*$"
                  this.telephoneForm = this.formBuilfer.group({
                    employee: [null, Validators.pattern(this.pattern), Validators.required ],
            })
            }
    

    above pattern will not accept space into input field and display error message in html like

    <div *ngIf="employee.errors?.pattern">
        employee is not valid.
    </div>