1

I have created a dynamic form using Angular that allows users to input email addresses. The user should not be allowed to add another empty field until the previous field is completed. Currently my code validates the first field correctly but will add a new field if the second, third, etc. is blank even though it will still fire the error alert.

Here is the HTML:

<ion-item id="row" *ngFor="let emailinput of emailinputs ; let i = index">
  <ion-label fixed id="label">
    Email
  </ion-label>
  <ion-input type="email" id="email" placeholder="[email protected]" [(ngModel)]="emailinputs[i].email"></ion-input>
</ion-item>

<div padding>
  <button (click) = "addnewemail(emailinputs)" ion-button full color="nudgetprim" block>Add</button>
  <button (click) = "sendinvite(emailinputs.email)" ion-button full color="nudgetprim" block>Invite</button>
</div>

Here is the TS:

addnewemail() {
  console.log(this.emailinputs)
  for(var a in this.emailinputs){
    if (this.emailinputs[a].email==null || this.emailinputs[a].email=="" || !this.emailinputs[a].email.includes("@") || !this.emailinputs[a].email.includes("."))
    {
      let alert = this.alerCtrl.create({
        title: 'Error!',
        message: 'There was an error with an email address you entered.',
        buttons: ['Ok']
      });
      alert.present()
    }
    else {
      var newItem = this.emailinputs.length;
      this.emailinputs.push({'id' : 'row' + newItem, 'name' : 'row' + newItem, 'email': ''});
    }
  }
}

How can I make this work for every input, not just the first?

2
  • Don't use the same id for multiple elements. Commented Dec 5, 2017 at 23:34
  • 1
    Why not use reactive forms and a FormArray? Commented Dec 5, 2017 at 23:49

1 Answer 1

1

You are now iterating the whole array, which means, if the code hits an item in your array that actually has values, it will add a new item in the array. What you want to check, is that the last item in your array does not have an empty (or invalid) email value:

addnewemail() {
  // get last item!
  let item = this.emailinputs[this.emailinputs.length-1];
    if (item.email == null || 
        item.email == "" || 
        !item.email.includes("@") || 
        !item.email.includes(".")) {
      // alert
    }
    else {
      // add new item
    } 
}

StackBlitz

You could also try and use actual email validation, preferably making a reactive form (like suggested in comment) with Validators.email.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.