Validation proposal
Ui-grid validation
I've started working on some kind of validation.
You can find a working proof of concept of what I've come up with and a short analysis of how I thought it should be.
Comments & suggestions are needed and welcome.
Guidelines
- Validation should be an external feature, just like navigation, grouping, importing, etc.
- Validation can safely rely on ui-grid.edit since validation would make little sense without editing capabilities.
- The end user should be able to insert a not valid value, and see a significant graphical hint that warned him about the invalidity of the inserted value (for example a red border).
- Given how users could interact with a grid (i.e. if doing data entry they could be editing many fields without even watching the screen), validation hints should be kept until the field is edited againg with a valid value.
- Validation could not rely on standard angular validation because of the way
ui-grid and angular ng-model works (please, correct me if I'm wrong):
- If we created a standard angular validation on a text input field, and the user inserted an invalid value, then the model would not update to the invalid value but would keep the original value.
- The user would thus see the field showing the old value but without being warned about the invalid value.
- The invalid value would be lost possibly causing loss of data.
- Validation would be based on a set of standard validator wich could be extended programmatically.
- Both standard and custom validation should be asyncronous.
How to add validation
-
Validation is added to the grid using
ui-grid-validatedirective and to the application injectingui.grid.validate. -
Validators are defined:
- A standard validator can be attached to a column declaring it as part of
columnDefsinside thegridOptions - A custom validator can be created and added to the standard ones for a
given column by calling the API method
addColumnValidator.
- A standard validator can be attached to a column declaring it as part of
-
To show the hint a custom template is needed. There are two readily available:
ui-grid/cellTitleValidatorui-grid/cellTooltipValidator
Both of them show a red border based on a
ng-classattribute whose job is to add theinvalidclass to invalid fields.
Furthermore they can show a list of error messages but they do so using different methods: the former uses thetitleattribute of the celldiv, while the latter depends on ui-bootstrap and uses atooltip.
How it works
-
Upon creation of the
ui-grid-validatedirective, theinitializeGridmethod is called wich:- catches the
afterCellEditevent fromui.grid.edit's API and binds it to therunValidatorsinternal method. - initializes an empty object
columnValidatorsfor anycolDef. - creates any standard validator if defined inside the
gridOptions.
- catches the
-
After editing of a field is over, the event
afterCellEditis raised andrunValidatorsis triggered. It cycles through any validator existing in thecolDefof the edited cell and asyncronously checks if it succeeds or fails. -
If anyone of the validator fails, the status is set to invalid by adding a
$$invalid<colDef.name>property to the rowEntity of the edited cell and an error cause is added to a$$errors<colDef.name>property as well, by using the followng methods:setInvalidsetError
If a validator succeeds, the error cause of that specific validator is removed from the error set calling
clearError.
If every validator succeeds, the status is set to valid removing the$$invalid<colDef.name>by callingsetValid. -
The newly created properties can be accessed using the following methods, in order to style the view and show validation warning and error messages to the user:
isInvalidgetFormattedErrorsgetTitleFormattedErrors
It is not full proof, I have tried, but without putting anything I can easily move out to cell. And then it is not showing red border. I am really struggling with different types of validations. Please suggest.
What do you mean @p7103934 ? Did you try this one? If it is so, as stated, validation was added to columns Age (null values are not acceptable) and Address - city (length < 3 is not acceptable). Is it possible you edited some other field instead?
I think the idea for having an ability to specify validators is great. However, I don't really like proposed api in the example. I think rather than having developer specify rules as a simple key/value object (validators: {notNull: true}) it'd be better to provide something more robust:
validators: {
notNull: { message: 'please provide a value', rule: function(val) { return !val; } },
max: { message: 'value is too long', rule: function(val) { return val < 50; } },
min: { message: 'value is too short', rule: function(val) { return val > 3; } }
}
By having the rule to be a function developer has a lot more flexibility.
Also, I think this needs to be under module edit since validation does not really make sense in any other context.
@DmitryEfimenko the key/value declaration is just a way to simplify the use of usual validators.
You can take a look in the code I wrote (and that I think we are gonna use in our project) and you can see here that the service exposes a broader addColumnValidator method.
I wouldn't like having complex rules inside the column definitions since they are already quite congested in a complex grid, so a service method is preferable to me.
As for where this should be, I think modularity is always great, especially for templates in this case.
Furthermore since I don't know where (and if) this would be eventually merged to master (and as I said we need it in an upcoming project) I preferred writing it in a different module in order to rebase it more easily.
The concept looks really nice. Couldn't make it work in the 3 minutes I had. One thing I think is missing is a full grid validation/action upon invalidation. For isntance, some would like the invalid value to remain, but to disable a "submit" button while others would like the value to revert to the former value... So I believe that an "action" could be another level of flexiblity for this feature. I'll check it more thoroughly later on. Good work :)
I kept on working on this and got to a new version.
The guidelines are the same, what's changed is the way to create and use validators.
Technically the previous version created a validator function for any column using it and then launched that very function (colDef.columnValidator was the real function).
Now the validators function are defined inside of the service and launched from there (colDef.columnValidator doesn't exist anymore).
Furthermore I added a method to create new validators easily (service.setValidator) and another one to get validators from an existing external service (validator function in that service should accept the same parameters as we do (it should work with validators built like angular standard ones where the parameters are viewValue and modelValue).
I'm doing a commit right now and then I think I'll make a pull request. I don't know if the interest in this is that low but maybe having it in master (obviously as alpha, for now) could stimulate some thought.
hello. the POC works fine, but I don't get why in the Guidelines you have this: Both standard and custom validation should be asyncronous.
I use the afterCellEdit handler to execute an ajax update, but because it calls runValidators asynchronously, I cannot prevent to execute my ajax post thanks to the extra properties $$invalid<> and $$error<>
Is there any other way to check?
I've finally found out a way to handle the "beforeSend" event through the inspector.
and using the promise, I can cancel the ajax request by using the timeout property of the $http bound to the $q.defer().promise:
angular.module('myapp').factory("interceptors", [function () {
return {
// if beforeSend is defined call it
'request': function (request) {
if (request.beforeSend) {
request.beforeSend();
}
return request;
},
// if complete is defined call it
'response': function (response) {
if (response.config.complete)
response.config.complete(response);
return response;
}
};
}]);
angular.module('myapp').config(["$httpProvider", function ($httpProvider) {
// register interceptors service
$httpProvider.interceptors.push("interceptors");
}]);
angular.module('myapp').controller('myCtrl', ['$scope', '$http', '$q', 'uiGridConstants', function ($scope, $http, $q, uiGridConstants) {
//..............
// further in the afterCellEdit
//..............
gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
if (oldValue !== newValue) {
var requestData = { obj: JSON.stringify(rowEntity) };
var canceler = $q.defer();
var rq = $http({
method: 'POST',
url: wdw.siteBaseUrl + "controller/action",
data: requestData,
timeout: canceler.promise,
// the beforeSend is triggered after the runValidators
beforeSend: function (q) {
if (true === rowEntity["$$invalid" + colDef.name]) {
rowEntity[colDef.field] = oldValue;
canceler.resolve();
}
else {
wdw.beginWait("myWaiter");
}
},
success: function (result) {
// nothing to do here
},
error: function(result) {
rowEntity[colDef.field] = oldValue;
},
complete: function () {
wdw.endWait("myWaiter");
}
});
return rq;
}
});
Even if the cel nav changed the focus, at least the input has the invalid class and the ajax request does not execute
There are 2 pretty common (in my opinion) scenarios that this doesn't cover.
- Validation of loaded data:
- Users often want to save their progress and continue work later. If you reload the grid - the only way I see to validate the data is to have the users re-edit those cells.
- Canceled edits:
- Its pretty normal to have an empty row for data entry. While you wouldn't want those cells to be flagged as invalid - you would want to flag them as soon interacts with them. For example, I'm using
cellNavwithenableCellEditOnFocus: true. This is a high volume data-entry user - the more they have to click - the worse. So anyways, I keep an empty row on the bottom - as soon as they start to edit it, a new empty row appears below. While they are tabbing through cells - editing some - not editing others, they tab through arequired: truecell without entering in any data. That doesn't get flagged as invalid because the event for tabbing through the cells without making changes iscancelEditCell.
- Its pretty normal to have an empty row for data entry. While you wouldn't want those cells to be flagged as invalid - you would want to flag them as soon interacts with them. For example, I'm using
Looking at the code, I'm not sure how you would support these two scenarios. I would think being able to define custom validation events would handle it. That would at least fix the cancelEditCell issue. As for validating the data on load - I don't know what events would work best for that. Also I don't know how I could validate the entire grid on load - but then exclude the empty row that is only there for new data.
Hi there. Is it possible to get a version of the ui-grid.js 3.1.1 including the validation poc ?
My requirement is similar to @lightswitch05 2nd scenario above (having a blank row to enter the data). Once users enters the data, I want an ability to validate the entire grid. Below is the code I am currently using for this. I feel this should be part of the library.
In addition I also want to get a promise when the validation is complete. If there are no validation errors, then I will push the data to the server. I couldn't find a way for this without going into the ui-grid code. Is there a workaround for this?
function validateGrid(gridOptions) {
angular.forEach(gridOptions.data, function (rowEntity) {
angular.forEach(gridOptions.columnDefs, function (colDef) {
gridOptions.gridApi.grid.validate.runValidators(rowEntity, colDef, rowEntity[colDef.field], undefined, gridOptions.gridApi.grid)
})
})
}
We found a much easier solution was to have each row link to a modal. Then use the AngularJS validation for the modal form. This solves the issue of having to scroll within the grid to fix errors since it is now only used to display validated data.
Above validation works on cell input value. What is the solution for complex validation? For example, you have 3 columns, ColA, ColB and ColC. If I enter any value in ColA, ColB's value should be required before saving the record. Or if I update value in ColB, it should validate some custom logic on ColC and if there is error in ColC's validation, it should show the error message on ColC's value (note, we have changed value in ColB, so our cursor would be in ColB's cell).
Also, above code, adds two properties i.e. $$error and $$invalid in rowEntity if value is invalid. Instead of that, is there anyway to set the entire row valid or invalid based on all the validations on input.
@parag-patil - You can manually trigger the validation for a column and row by the following code
gridOptions.gridApi.grid.validate.runValidators(rowEntity, colDef, rowEntity[colDef.field], undefined, gridOptions.gridApi.grid)
I went through the official docs and could found only simple validators i.e. maxlength and minlength. Is this all to the validations we have for now. Isn't it possible to provide more of them, like positive numbers, negative numbers, decimal numbers etc. If they exist where can I find a complete list of supported validations?