0

Here I have one input field when I click on SAVE button it goes in saveNewCategory() function and check it is null or not, but when I put only spaces in input field that time also it is saved so how it is not allowed to save input field when only spaces is given in the input field?

category.component.html

<div>
  <form method="post" enctype="multipart/form-data">
    <mat-form-field>
     <input matInput placeholder="Category Title" maxlength="30" name="categorytitle" [(ngModel)]="this.categoryObj.categorytitle" required>
    </mat-form-field>
  </form>
  <button mat-raised-button color= "accent" (click)="saveNewCategory()">SAVE</button>
</div>

category.component.ts

saveNewCategory(){
  if(this.categoryObj.categorytitle != ''){
    const formData = new FormData();
    formData.append('categorytitle',this.categoryObj.categorytitle);
    this.categoryService.saveNewCategory(formData).subscribe(
      (data) => {
        if(data != undefined && data.status == 1){
          this.snackBar.open('New Category Saved Successfully..!!', '',{
            duration: 2000
          });  
        }
      }
    )
  }else{
    this.snackBar.open('Category Image is required..!!', '',{
      duration: 2000
    });  
  }  
} 
Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46
Dharmesh
  • 5,383
  • 17
  • 46
  • 62
  • Possible duplicate of [How can I determine if a string only contains spaces, using javascript?](https://stackoverflow.com/questions/10528193/how-can-i-determine-if-a-string-only-contains-spaces-using-javascript) – yannick Oct 19 '18 at 06:15
  • @yannick instead of jquery what i have to use here ? – Dharmesh Oct 19 '18 at 06:19
  • !this.categoryObj.categorytitle.trim().length == 0 – yannick Oct 19 '18 at 06:21

1 Answers1

1

You can use trim method as:

saveNewCategory(){
  if(this.categoryObj.categorytitle.trim() != ''){ <===== Here
    const formData = new FormData();
    formData.append('categorytitle',this.categoryObj.categorytitle);
    this.categoryService.saveNewCategory(formData).subscribe(
      ...
    )
  }else{
    ...
  }  
} 
Anshuman Jaiswal
  • 5,352
  • 1
  • 29
  • 46