Uday Reddy
Uday Reddy

Reputation: 1471

Validate date in ui-grid

I am using ui-grid

One of my columns have date type. How do I validate date by only accepting future dates?

Thanks.

Upvotes: 1

Views: 1469

Answers (2)

Afifa Rih
Afifa Rih

Reputation: 191

You have to add a custom validator according to this tutorial, in your case it should be like this:

  1. Add 'ui-grid-validate' directive to ui-grid tag in HTML

    <div ui-grid="gridOptions" ui-grid-edit ui-grid-cellNav ui-grid-validate        
    class="grid"></div>
    
  2. Inject 'uiGridValidateService' service in the controller .js

    app.controller('MainCtrl', ['$scope', 'uiGridValidateService', function ($scope, uiGridValidateService)
    
  3. Declare column definition of the date like this:

    $scope.gridOptions.columnDefs = [
       //other columns
       { name: 'myDate', displayName: 'my date',  
       validators: {
             required: true, compareDateNow: ''
       }, 
       cellTemplate: 'ui-grid/cellTitleValidator' }
    ];
    
  4. Implement your validate methode which comares between the cell value and current date:

    uiGridValidateService.setValidator('compareDateNow', 
      function (argument){
        return function (oldValue, newValue, rowEntity, colDef) {
            if (!newValue) {
                return true;
            } else {
                return (newValue >= Date.now());
            }
        };
      },
      function (argument) {
        return 'error message';
      }
    );
    

Upvotes: 2

PaulL
PaulL

Reputation: 6650

Presumably you are using the editable module? The standard date editor looks to only accept valid dates.

If you want something more than this, you would define a new directive for a special date editor, and include validation within that directive. When creating a new directive you want to make sure you provide the mandatory EDIT events, refer the tutorial for more information: http://ui-grid.info/docs/#/tutorial/201_editable

Upvotes: 1

Related Questions