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

前端 未结 18 2070
遇见更好的自我
遇见更好的自我 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 20:00

    I think a simple and clean solution is to use pattern validation.

    The following pattern will allow a string that starts with white spaces and will not allow a string containing only white spaces:

    /^(\s+\S+\s*)*(?!\s).*$/
    

    It can be set when adding the validators for the corresponding control of the form group:

    const form = this.formBuilder.group({
                name: ['', [
                    Validators.required,
                    Validators.pattern(/^(\s+\S+\s*)*(?!\s).*$/)
                ]]
            });
    

提交回复
热议问题