最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 4 button disabled even if the form has valid values - Stack Overflow

programmeradmin11浏览0评论

I am have created a Reactive Form which is know as signupForm which has different values here is the code

 signupForm = new FormGroup({
    name : new FormControl('',[Validators.required,Validators.maxLength(20)]),
    email : new FormControl('',[Validators.required,Validators.maxLength(20),Validators.pattern('/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/')]),
    username: new FormControl('',[Validators.required,Validators.minLength(5)]),
    password : new FormControl('',[Validators.required,Validators.minLength(8),Validators.maxLength(20)]),
    usermobile: new FormControl('',[Validators.required]),
    usercompany: new FormControl('',[Validators.maxLength(50)]),
    usercity: new FormControl('',[Validators.maxLength(20)]),
    usercountry:new FormControl('IN'),
    websiteurl: new FormControl(''),
    usertype: new FormControl('1')
  });

 onSubmit(){
   let udata= {}
   udata = this.signupForm.value;
   this._httpService.signup(udata).subscribe((result)=>{
     console.log(result);
   })
 }

 checkusername(event){
   let data = event.target.value;
   if (data != '') {
    this._httpService._username(data)
      .subscribe((result) => {
        if (result.status == "sucess") {
          this.username_check = true;
        } else {
          this.username_check = false;
        }
      },
      (err: any) => {
        if (err.status == 0) { console.log('please check your internet connection'); }
        else if (err.status == 500) { console.log('oops something went wrong, please try again!!'); }
      },
      () => console.log());
  }
 }

 clearMsgForUsername() {
  this.username_check = true;
}

My HTML code were i am using the reactive form , here is my submit button which is disabled even if i enter all the details correctly

   <form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
            <div id="signin-form" class="login-form animated preFadeInLeft fadeInLeft">
              <!-- Input -->
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="name" class="input is-large" type="text" placeholder="Name">
                </div>
                <div *ngIf="signupForm.controls['name'].hasError('required')  && (signupForm.controls['name'].dirty || signupForm.controls['name'].touched)"
                  class="error">
                  Please enter a password
                </div>
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="email" class="input is-large" type="email" placeholder="Email">
                </div>
                <div *ngIf="signupForm.controls['email'].hasError('required') && (signupForm.controls['email'].dirty || signupForm.controls['email'].touched)"
                  class="error">
                  Please Enter a valid email
                </div>
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="username" (blur)="checkusername($event)" (keyup)="clearMsgForUsername()" class="input is-large" type="text" placeholder="Username">
                </div>
                <div *ngIf="signupForm.controls['username'].hasError('required') && (signupForm.controls['username'].dirty || signupForm.controls['username'].touched)"
                  class="error">
                   Username is required
                </div>
                <div *ngIf="!username_check" class="error">
                    Already associated with a different account.
                  </div>
              </div>
              <!-- Input -->
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="password" class="input is-large" type="password" placeholder="Password">
                </div>
                <div *ngIf="signupForm.controls['password'].hasError('required') && (signupForm.controls['password'].dirty || signupForm.controls['password'].touched)"
                  class="error">
                   Password is required
                </div>
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="usermobile" class="input is-large" type="text" placeholder="Mobile">
                  <div *ngIf="signupForm.controls['usermobile'].hasError('required')&&(signupForm.controls['usermobile'].dirty || signupForm.controls['usermobile'].touched)"
                  class="error">
                   Please Enter a Mobile Number
                </div>
                </div>
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="usercompany" class="input is-large" type="text" placeholder="Company">
                </div>
               <!-- <div *ngIf="signupForm.controls['usercompany'].dirty && signupForm.controls['usercompany'].touched"
                  class="error">
                    This field is optional if you are a freelancer
                </div> -->
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="usercity" class="input is-large" type="text" placeholder="City">
                </div>
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="websiteurl" class="input is-large" type="text" placeholder="Website">
                </div>
              </div>
              <!--Input-->
              <!--Input-->
              <div class="field">
                <div class="control required">
                  <div class="select is-large">
                    <select formControlName="usertype">
                      <option value="1">Freelancer</option>
                      <option value="2">Company</option>
                    </select>
                  </div>
                </div>
              </div>
              <!-- Submit -->
              <p class="control login">
                <button type="submit" [disabled]="!signupForm.valid" class="button button-cta primary-btn btn-align-lg btn-outlined is-bold is-fullwidth rounded raised no-lh">Signup</button>
              </p>
            </div>
          </form>

When i try to fill all the values the signup button is disabled even all the values has been filled properly in the form

I am have created a Reactive Form which is know as signupForm which has different values here is the code

 signupForm = new FormGroup({
    name : new FormControl('',[Validators.required,Validators.maxLength(20)]),
    email : new FormControl('',[Validators.required,Validators.maxLength(20),Validators.pattern('/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/')]),
    username: new FormControl('',[Validators.required,Validators.minLength(5)]),
    password : new FormControl('',[Validators.required,Validators.minLength(8),Validators.maxLength(20)]),
    usermobile: new FormControl('',[Validators.required]),
    usercompany: new FormControl('',[Validators.maxLength(50)]),
    usercity: new FormControl('',[Validators.maxLength(20)]),
    usercountry:new FormControl('IN'),
    websiteurl: new FormControl(''),
    usertype: new FormControl('1')
  });

 onSubmit(){
   let udata= {}
   udata = this.signupForm.value;
   this._httpService.signup(udata).subscribe((result)=>{
     console.log(result);
   })
 }

 checkusername(event){
   let data = event.target.value;
   if (data != '') {
    this._httpService._username(data)
      .subscribe((result) => {
        if (result.status == "sucess") {
          this.username_check = true;
        } else {
          this.username_check = false;
        }
      },
      (err: any) => {
        if (err.status == 0) { console.log('please check your internet connection'); }
        else if (err.status == 500) { console.log('oops something went wrong, please try again!!'); }
      },
      () => console.log());
  }
 }

 clearMsgForUsername() {
  this.username_check = true;
}

My HTML code were i am using the reactive form , here is my submit button which is disabled even if i enter all the details correctly

   <form [formGroup]="signupForm" (ngSubmit)="onSubmit()">
            <div id="signin-form" class="login-form animated preFadeInLeft fadeInLeft">
              <!-- Input -->
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="name" class="input is-large" type="text" placeholder="Name">
                </div>
                <div *ngIf="signupForm.controls['name'].hasError('required')  && (signupForm.controls['name'].dirty || signupForm.controls['name'].touched)"
                  class="error">
                  Please enter a password
                </div>
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="email" class="input is-large" type="email" placeholder="Email">
                </div>
                <div *ngIf="signupForm.controls['email'].hasError('required') && (signupForm.controls['email'].dirty || signupForm.controls['email'].touched)"
                  class="error">
                  Please Enter a valid email
                </div>
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="username" (blur)="checkusername($event)" (keyup)="clearMsgForUsername()" class="input is-large" type="text" placeholder="Username">
                </div>
                <div *ngIf="signupForm.controls['username'].hasError('required') && (signupForm.controls['username'].dirty || signupForm.controls['username'].touched)"
                  class="error">
                   Username is required
                </div>
                <div *ngIf="!username_check" class="error">
                    Already associated with a different account.
                  </div>
              </div>
              <!-- Input -->
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="password" class="input is-large" type="password" placeholder="Password">
                </div>
                <div *ngIf="signupForm.controls['password'].hasError('required') && (signupForm.controls['password'].dirty || signupForm.controls['password'].touched)"
                  class="error">
                   Password is required
                </div>
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="usermobile" class="input is-large" type="text" placeholder="Mobile">
                  <div *ngIf="signupForm.controls['usermobile'].hasError('required')&&(signupForm.controls['usermobile'].dirty || signupForm.controls['usermobile'].touched)"
                  class="error">
                   Please Enter a Mobile Number
                </div>
                </div>
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="usercompany" class="input is-large" type="text" placeholder="Company">
                </div>
               <!-- <div *ngIf="signupForm.controls['usercompany'].dirty && signupForm.controls['usercompany'].touched"
                  class="error">
                    This field is optional if you are a freelancer
                </div> -->
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="usercity" class="input is-large" type="text" placeholder="City">
                </div>
              </div>
              <div class="field pb-10">
                <div class="control required">
                  <input formControlName="websiteurl" class="input is-large" type="text" placeholder="Website">
                </div>
              </div>
              <!--Input-->
              <!--Input-->
              <div class="field">
                <div class="control required">
                  <div class="select is-large">
                    <select formControlName="usertype">
                      <option value="1">Freelancer</option>
                      <option value="2">Company</option>
                    </select>
                  </div>
                </div>
              </div>
              <!-- Submit -->
              <p class="control login">
                <button type="submit" [disabled]="!signupForm.valid" class="button button-cta primary-btn btn-align-lg btn-outlined is-bold is-fullwidth rounded raised no-lh">Signup</button>
              </p>
            </div>
          </form>

When i try to fill all the values the signup button is disabled even all the values has been filled properly in the form

Share Improve this question asked Apr 25, 2018 at 11:11 Rohit JainRohit Jain 651 gold badge1 silver badge10 bronze badges 2
  • have you rendered the valid property of each fields and verified ? see if all fields are true. – Shashank Vivek Commented Apr 25, 2018 at 11:15
  • 2 Try to remove one form at a time, to see when the button is being enabled. Or even better, start with one form, and gradually add more forms until your button still is disabled. – John Commented Apr 25, 2018 at 11:15
Add a comment  | 

2 Answers 2

Reset to default 9

It seems it comes from your email regex. I reproduced your example (simplified) here, and it seems that the email formControl isn't valid.

To debug your forms you can log the form controls in your view like I done in the example:

<!-- DEBUG -->
<pre>{{signupForm.get('name').valid}}</pre>
<pre>{{signupForm.get('email').valid}}</pre>
<pre>{{signupForm.get('username').valid}}</pre>
<pre>{{signupForm.get('password').valid}}</pre>
<pre>{{signupForm.get('usermobile').valid}}</pre>
<pre>{{signupForm.get('usercompany').valid}}</pre>
<pre>{{signupForm.get('usercity').valid}}</pre>
<pre>{{signupForm.get('usercountry').valid}}</pre>
<pre>{{signupForm.get('websiteurl').valid}}</pre>
<pre>{{signupForm.get('usertype').valid}}</pre>

It renders like that in your view in order to let you debug it (e.g.):

false
false
true
false
false
true
true
true
true
true

EDIT:

It appears that you forgot the g flag after your email regex. So adding it at the end of the regex seems to make it work. I updated the example.

So now your regex is like (notice the g after it):

/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/g

For debug

console.log(this.signupForm);

In console, under FormGroup -> controls -> input element name -> status

if status as INVALID check with

FormGroup -> controls -> input element name -> errors
发布评论

评论列表(0)

  1. 暂无评论