0

I'm trying to create an email centre using the regex pattern but I'm getting an error in validator in HTML. Installed ngx-chips and angular-editor, imported all the modules and the dependencies

HTML-

<div class="row class-spacing">
    <div class="col-2">To</div>
    <div class="col-8 set-border">
      <tag-input
        [ngModel]="toEmails"
        [displayBy]="'label'"
        [identifyBy]="'label'"
        [theme]="'bootstrap'"
        name="toEmails"
        placeholder="+ To"
        [separatorKeyCodes]="[32, 188]"
        secondaryPlaceholder="To"
        [errorMessages]="errorMessages"
        [validators]="validators"
        [removable]="true"
      >
        <tag-input-dropdown
          [dynamicUpdate]="false"
          [zIndex]="10000"
          [displayBy]="'label'"
          [identifyBy]="'label'"
          [showDropdownIfEmpty]="true"
        >
          <ng-template let-item="item" let-index="index">
            {{ item.label }}
          </ng-template>
        </tag-input-dropdown>
      </tag-input>
    </div>
  </div>

The TypeScript file-

export class EmailComponent implements OnInit {
public errorMessages = {
pattern: 'Email must be in format abc@abc.com',
};
public validators = (this.checkPattern);

@ViewChild('form', { static: false })
form!: NgForm;
public dataModel: any;
public editorTextCount = 0;
public isSubmitted: boolean = false;
public isFieldEmpty: boolean = false;
public isMaxLengthLimitReached: boolean = false;
public config: AngularEditorConfig = {
editable: true,
spellcheck: true,
height: '200px',
width: 'auto',
enableToolbar: true,
showToolbar: true,
placeholder: 'Enter your email',
fonts: [
  { class: 'arial', name: 'Arial' },
  { class: 'times-new-roman', name: 'Times New Roman' },
  { class: 'calibri', name: 'Calibri' },
],
sanitize: true,
toolbarPosition: 'top',
toolbarHiddenButtons: [
  [],
  ['customClasses', 'insertImage', 'insertVideo', 'toggleEditorMode'],
],
};
body: any;
subject: any;
toEmails: any;

public formDetails = {
toEmails: '',
subject: '',
body: '',
};
public items = ['Pizza', 'Pasta', 'Parmesan'];
constructor() {}

ngOnInit() {}

public sendEmail(): void {
console.log(this.form.value);
}

private checkPattern(control: FormControl) {
const patternRegex = /^[A-Za-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;
if (patternRegex.test(control.value)) {
  return console.log('Match exists.');
} else {
  return { pattern: true };
}
}
}

The error I'm getting in the line-

[validators]="validators"

The error I'm getting-

Type '(control: FormControl) => void | { pattern: boolean; }' is not assignable to type 'ValidatorFn[]'.

Ayush Rai
  • 11
  • 3
  • You should not write your own regex to validate emails. Most regex developers come up with are incomplete, will reject totally valid addresses and therefore discriminate against some users. See here for the correct HTML 5 regex: https://stackoverflow.com/a/7791100/608042. A better way would be to rely on the browser’s own validation. `const i = document.createElement('input'), i.type='email', i.required = true, i.value = control.value, return i.checkValidity()` – Andy Jan 20 '23 at 14:30

1 Answers1

0

Implement a custom validator function requires:

  • Only one input argument is expected, which is of type AbstractControl. The validator function can obtain the value to be validated via the control.value property

  • The validator function needs to return null if no errors were found in the field value, meaning that the value is valid

  • If any validation errors are found, the function needs to return an object of type ValidationErrors

Reference: Angular Custom Form Validators: Complete Guide (How to write a Validator function section)

private checkPattern(): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const patternRegex = /^[A-Za-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/;
    if (patternRegex.test(control.value)) {
      console.log('Match exists.');
      return null;
    } else {
      return { pattern: true };
    }
  };
}

Assign validators with a ValidatorFn array containing checkPattern ValidatorFn.

public validators = [this.checkPattern];
Yong Shun
  • 35,286
  • 4
  • 24
  • 46