How to validate white spaces/empty spaces? [Angular 2]

前端 未结 18 2149
遇见更好的自我
遇见更好的自我 2020-12-04 19:14

I would like to avoid white spaces/empty spaces in my angular 2 form? Is it possible? How can this be done?

18条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-04 19:56

    i have used form valueChanges function to prevent white spaces. every time it will trim all the fields after that required validation will work for blank string.

    Like here:-

    this.anyForm.valueChanges.subscribe(data => {
       for (var key in data) {
            if (data[key].trim() == "") {
              this.f[key].setValue("", { emitEvent: false });
            }
          }
        }
    

    Edited --

    if you work with any number/integer in you form control in that case trim function will not work directly use like :

    this.anyForm.valueChanges.subscribe(data => {
      for (var key in data) {
            if (data[key] && data[key].toString().trim() == "") {
              this.f[key].setValue("", { emitEvent: false });
            }
          }  
      }
    

提交回复
热议问题