Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular/Javascript - return the correct number onKeyUp

Tags:

I am trying to check the email validity (when the user start typing onkeyup), then if the email is valid I push it into an array of unique emails; however, I stop pushing to the array once it reaches a certain number, in my case it's 3.

     <textarea (ngModelChange)="onKeyUp($event)"></textarea>

     onKeyUp(ev) {

      let finalEmailList = []
      this.finalEmailList = [];

      this.numberOfUsers = 3;

      let emails = ev.replace(' ', '').split(/,| /);

      emails.forEach(email => {
        if (this.validateEmail(email)) {
          //If the email has a valid format, the push it to the array
          finalEmailList.push(email);
          //it's a lodash function to clean the array an keep only unique emails in the array
          this.finalEmailList = _.uniq(finalEmailList);

           if (this.finalEmailList.length <= this.numberOfUsers) {
          this.numberOfUsers -= this.finalEmailList.length;
          }
        }
      })
    }

  //returns true if the email has a valid format
  validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\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,}))$/;
    return re.test(email);
  }

The issue:

I believe it's a wrong way to do it as on each and every letter printed from the keyboard everything runs again and again, resetting variables, running for loops, etc...

Also the value returned for this.numberOfUsers is not correct.

like image 307
Folky.H Avatar asked May 16 '18 23:05

Folky.H


People also ask

What does onKeyUp mean in Javascript?

The onkeyup attribute fires when the user releases a key (on the keyboard).

What is the difference between onKeyUp and onKeyDown?

The onKeyDown event is triggered when the user presses a key. The onKeyUp event is triggered when the user releases a key.

What does Keyup do in angular?

(keyup) is an Angular event binding to respond to any DOM event. It is a synchronous event that is triggered as the user is interacting with the text-based input controls. When a user presses and releases a key, the (keyup) event occurs.


1 Answers

If you want the email address to be complete before validating, validating onBlur as others have suggested may be your best course of action. Another option is to continue listening for onKeyUp, but only trigger validation if the key is a specific trigger key.

Example:

onKeyUp(event) {
  if ([13, 188].includes(event.keyCode)) {
    validateEmails()
  }
}

In this example, 13 and 188 are the key codes for Enter and comma, respectively.

like image 50
Michael Barrett Avatar answered Sep 20 '22 08:09

Michael Barrett