SlickGrid Validation

Validation in SlickGrid is another of those features that's pretty sparsely documented. Validation pops up a few times in the examples, but that's about it. Having read various posts on the subject scattered around the internet most people's take-away from the examples seems to be that they set the validator as per this example: http://mleibman.github.io/SlickGrid/examples/example3-editing.html. Then they complain that it doesn't provide any flexibility, as the only thing passed to the function is the value of the cell. What if I need something more advanced they ask?

Well that's where the documentation should tell you that actually the 'validator' in that example is simply a function of the Slick.Editors.Text editor, and you can write your own editor (or adjust an existing one) to include whatever validation you desire (though SlickGrid validation is always cell by cell). A lot of people seem to miss that the editors are meant to be customised, and I put this down to the fact most of the documentation for SlickGrid is made up of examples, provided with little or no explanation.

Custom validation & custom editors

The first thing you'll want to do is wrap your head around how to create your own editor. Open up slick.editors.js and have a look around. If you want to add a new editor it goes in there as a function, then you register it at the top of the file e.g. adding the function MyEditor:

// register namespace
$.extend(true, window, {
  "Slick": {
    "Editors": {
      "Text": TextEditor,
      "Integer": IntegerEditor,
      "My": MyEditor,
      "Date": DateEditor,
      "YesNoSelect": YesNoSelectEditor,
      "Checkbox": CheckboxEditor,
      "PercentComplete": PercentCompleteEditor,
      "LongText": LongTextEditor
    }
  }
});
function MyEditor(args) {
  ...
}

Once you've done that you can use your editor as you do the default ones by adding 'editor: Slick.Editors.My' into your column definition.

As we're talking about validation, rather than the whole editor, just copy one of the existing editors (e.g. TextEditor or IntegerEditor) and have a look at the validate function. You can either do all your validation there (as per IntegerEditor), in which case validation is always performed the same way whenever you use that editor, or you can call args.column.validator (as per TextEditor). This means you have to define a validation function when you use your editor, but it gives you more flexibility. I prefer the latter option. You can pass whatever you like to args.column.validator, much more than just the input value as TextEditor uses by default. For example if you pass through args you will have access to pretty much everything you'll ever need to validate a cell and much more besides.

Once you have your editor ready to go you just add a validation function to your grid as per the earlier mentioned example, and that's it. Custom validation with access to much more than just the value of the cell.