How to set the validator function in dojo programatically

292 Views Asked by At

I have isDuplicate() function that I need to set as the validator function for my ValidationTextBox. So That's what I am doing:

parent=this;
var structure = [
            {"id": "Name", "field": "Name", "name": "Name", width: "40%",
                widgetsInCell: true,
                 alwaysEditing: true,
                 editor: ValidationTextBox,
                 editorArgs: {
                     props: 'required:true, validator: parent.isDuplicate ,invalidMessage:"Duplicate Name"'                          

                 }

I am receiving this error: Can not set cell value: TypeError: undefined is not a function

1

There are 1 best solutions below

0
On

You have a scope issue. When props is processed by the ValidationTextBox the parent variable is no longer visible. Since I myself have been unable to determine a decent means of handling the scope within the props string, I've found the easiest solution is to wrap the widget to curry the context to the widget constructor:

define(['dojo/_base/declare', 'dijit/form/ValidationTextBox'], function (declare, ValidationTextBox) {
  return function (validationContext) {
    return declare('DuplicateEntryValidationTextBox', [ValidationTextBox], {
      validationContext: validationContext,
      validator: function (value, constraints) {
        validationContext.isDuplicate(value, constraints);
      }
    })
  }
});

...

editor = DuplicateEntryValidationTextBox(parent),

OR using an IIFE:

editor: (function (validationContext) {
  return declare('DuplicateEntryValidationTextBox', [ValidationTextBox], {
    validationContext: validationContext,
      validator: function (value, constraints) {
      return validationContext.isDuplicate(value);
    }
  });
})(parent),

I know this probably doesn't help you, being almost a full year later, but I figured it'd be worth posting since I ran into the exact same issue.