Search code examples
javascriptangularangular6handsontable

How to add custom validations for handsontable in angular 2+


I'm using handsontable in angular 6.

I tried the code to add custom validations which is shown in the official documentation in my angular 6 component but it didn't work.

I searched several sites, but didn't find any single example that shows how to add custom validations in angular 2+ versions for handsOntable

Can anyone let me know how to register custom validations in angular 2+ versions

Thanks in advance :)


Solution

  • Created a sample custom validator for email and was able to set to a column

    emailValidator = (value, callback) => {
      console.log(value)
      setTimeout(function(){
        if (/.+@.+/.test(value)) {
          callback(true);
        }
        else {
          callback(false);
        }
      }, 1000);
    };
    
    private columns: any[] = [
    {
      data: 'name'
    },
    {
      data: 'email',
      validator: this.emailValidator,
      // Uncomment below line accept invalid input and indicate
      // allowInvalid: true
    }
    ];
    
    @ViewChild(HotTableComponent) hotTableComponent;
    // Call validator after initialization
    afterInit() {  this.hotTableComponent.getHandsontableInstance().validateCells(function(valid){});
    

    afterInit is an event emitter

    <hot-table [data]="data"
           [colHeaders]="colHeaders"
           [columns]="columns"
           [options]="options"
           (hotInstanceCreated)="instanceCreated($event)"
           (afterInit)="afterInit(event$)"
           [colWidths]="colWidths">
    

    https://stackblitz.com/edit/angular-kjmvq4?file=app%2Fapp.component.ts