Thursday 28 February 2019

Validator on add and without clearing (ngx-chips, angular)

I'm using ngx-chips to add a list of emails as tags into an input. A validator makes sure that each tag appears like an email.

How can I make sure that:

1) The validator only triggers when a tag is being added (i.e., user hits enter, space or comma)

2) If the email is not valid when enter/space/comma is hit, that the value persists (i.e., it does not clear...so that the user can fix it)

A stackblitz is here: https://stackblitz.com/edit/ngx-chips-example-2qdudc

Below is my email validator:

public validators = [ this.must_be_email ];
  public errorMessages = {
      'must_be_email': 'Please be sure to use a valid email format'
  };
  private must_be_email(control: FormControl) {        
      var EMAIL_REGEXP = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,3}$/i;
      if (control.value.length != "" && !EMAIL_REGEXP.test(control.value)) {
          return { "must_be_email": true };
      }
      return null;
  }

Below is the tag:

<tag-input [(ngModel)]='emails' 
name="emails" 
#email="ngModel" 
[errorMessages]="errorMessages"
[validators]="validators" 
[editable]='true' 
(onTagEdited)="onTagEdited($event)" 
[separatorKeyCodes]="[32,188,186,13,9]"
[placeholder]="'Add email'" 
[secondaryPlaceholder]="'Enter email address(es)'" 
[clearOnBlur]="true" 
[addOnPaste]="true"
[addOnBlur]="true"
[pasteSplitPattern]="splitPattern" 
theme='bootstrap' 
required >
</tag-input>

For 2), I tried changing "return null" to control.value in the validator...but that did not work



from Validator on add and without clearing (ngx-chips, angular)

No comments:

Post a Comment