Upon observation, it is evident that the default validation mechanism of Slickgrid is confined to the validate
function of an editor. This function primarily checks for the presence of a validator
and passes only the value as a parameter. To incorporate additional context-specific information, a custom editor or, more precisely, a custom validation function becomes necessary.
this.validate = function() {
if (args.column.validator) {
args.newValue = $input.val()
var validationResults = args.column.validator(args);
if (!validationResults.valid) {
return validationResults;
}
}
return { valid: true, msg: null };
};
For each column, a validator must be implemented where the default value is compared against either a new input from the editor or the existing value in addition to other validation criteria required.
var Validator = function(args) {
// Validate the existing value or the incoming editor value
var value = args.newValue ? args.newValue : args.item[args.column.field]
var result = value > 0
return {valid: result}
}
To validate the entire grid, a validation method should be created to iterate over every row and examine each column for a validator. Based on the validation outcomes, a mapping of
rowIndex -> collection of failures
is constructed to be forwarded to the native
onValidationError
event. This allows for monitoring errors and notifying users accordingly. Furthermore, the validation results can be utilized to apply specific styling to highlight failures by
providing unique metadata to the grid.
var validateColumns = function(args){
var failures=[];
for (c in columns) {
var column = columns[c]
if (column.validator) {
if(!column.validator({row: args.row, item: args.item, column: column}).valid){
failures.push({columnIndex: c, column: column, rowIndex: args.row, item: args.item})
}
}
}
return failures;
}
grid.validate = function() {
var rowFailures = {}
for (r in data) {
// Ignore the metadata provider (if applicable)
if(r == 'getItemMetadata'){continue;}
var failures = validateColumns({item: data[r], row: r})
if(failures.length > 0){
rowFailures[r] = failures;
}
}
if(Object.keys(rowFailures).length > 0){
grid.onValidationError.notify({"rowFailures": rowFailures}, new Slick.EventData())
}
}