# Server Data Validation

Canonical page: https://www.adaptabletools.com/docs/handbook-validating-server

- Server-side validation can be used to validate (and undo) Edits via a function
- An optional Message can be displayed to the User

AdapTable provides Server Validation, i.e. validation through a function provided by the user.

AdapTable also offers [Client Validation](https://www.adaptabletools.com/docs/handbook-validating-client/index.md) where the validation is handled using Validation Alerts

This is available via the `validateOnServer` property in [Edit Options](https://www.adaptabletools.com/docs/technical-reference-editing/index.md).

If provided, the _async_ function will be invoked by AdapTable each time a cell is edited.

This function will only be called **after** [Client Validation](https://www.adaptabletools.com/docs/handbook-validating-client/index.md) has successfully completed

The function receives full details of the proposed edit and returns one of 3 outcomes for `newCellValue`:

- **nothing** (empty result) — the edit is valid, or you will update data via the API or another mechanism
- the **old** value — validation failed; return the cell to its previous value
- a **different** value — often used when the new value breaches upper or lower bounds (see example below)

### `validateOnServer`

Runs Validation of Data Edits on the Server

```ts
validateOnServer?: (serverValidationContext: ServerValidationContext) => Promise<ServerValidationResult>;
```

**ServerValidationContext**

The function receives a [`ServerValidationContext`](https://www.adaptabletools.com/docs/reference/servervalidationcontext.md) object which wraps a [`CellDataChangedInfo`](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md) object.

This provides details of the old and new cell values, the cell's containing column and the relevant row node.

| Property | Type | Description |
| --- | --- | --- |
| [changedAt](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md#changedat) | `number` | Timestamp of change occurrence (in milliseconds) |
| [column](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md#column) | [`AdaptableColumn`](https://www.adaptabletools.com/docs/reference/adaptablecolumn.md)`<TData>` | Column in which cell is situated |
| [newValue](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md#newvalue) | `any` | Value after the change.<br/><br/>Absent when `trigger` is `live`. |
| [oldValue](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md#oldvalue) | `any` | Value before the change.<br/><br/>Absent when `trigger` is `live`. |
| [preventEdit](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md#preventedit) | `boolean` | Whether the change was prevented by a validation rule |
| [primaryKeyValue](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md#primarykeyvalue) | `any` | Primary Key Column&#39;s value for the row where edited cell is situated |
| [rowData](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md#rowdata) | `TData` | Data in the Row |
| [rowNode](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md#rownode) | `IRowNode<TData>` | AG Grid RowNode that contains the cell |
| [trigger](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md#trigger) | `'edit' \| 'tick' \| 'undo' \| 'aggChange' \| 'calculatedColumnChange' \| 'live'` | What triggered the change - user, background change, a reverted change, a<br/>derived update on a Calculated Column whose source value changed, or a<br/>live Alert rule turning true for the row (`live`: no old / new value,<br/>`column` is the rule&#39;s first Scope column when it has one). |

**ServerValidationResult**

The function returns a Promise containing a [`ServerValidationResult`](https://www.adaptabletools.com/docs/reference/servervalidationresult.md) object:

| Property | Type | Description | Default |
| --- | --- | --- | --- |
| [messageType](https://www.adaptabletools.com/docs/reference/servervalidationresult.md#messagetype) | [`AdaptableMessageType`](https://www.adaptabletools.com/docs/reference/adaptablemessagetype.md) | Type of Message to Display | Info |
| [newCellValue](https://www.adaptabletools.com/docs/reference/servervalidationresult.md#newcellvalue) | `any` | Cell Value to use for after Server Validation |   |
| [validationHeader](https://www.adaptabletools.com/docs/reference/servervalidationresult.md#validationheader) | `string` | Header to diplay with validation | &#39;Server Validation Message&#39;, |
| [validationMessage](https://www.adaptabletools.com/docs/reference/servervalidationresult.md#validationmessage) | `string` | Message to diplay with validation |   |

The `newCellValue` property is the value to use in the cell **instead** of the one proposed by the cell edit.

You can retrieve the previous value through the `oldValue` property of [`CellDataChangedInfo`](https://www.adaptabletools.com/docs/reference/celldatachangedinfo.md)

Optional notification fields on the same object:

| Property            | Description                                                         | Behaviour if not supplied             |
| ------------------- | ------------------------------------------------------------------- | ------------------------------------- |
| `validationHeader`  | Header of the Message                                               | Header is "Server Validation Message" |
| `validationMessage` | Text of the Message                                                 | No Notification is displayed          |
| `messageType`       | Defines the [`MessageType`](https://www.adaptabletools.com/docs/reference/adaptablemessagetype.md) to use | Uses default of _Info_                |

Notification behaviour (location, duration, etc.) follows [Notification Options](https://www.adaptabletools.com/docs/technical-reference-notifications/index.md).

A notification is shown only when `displayServerValidationMessages` is **true** in [Edit Options](https://www.adaptabletools.com/docs/technical-reference-editing/index.md) (the default) **and** the result includes a `validationMessage`.

### `displayServerValidationMessages`

Displays a Notification Message after Server Validation

If true, an Info Message appears with ValidationMessage sent by ServerValidation.

```ts {3}
editOptions: {
  // Don't allow any Server Validation Messages to be displayed
  displayServerValidationMessages: false
},
```

If `validateOnServer` returns no validation message, no message is displayed even when this value is true

**Example: Server Validation**

Performing Server Validation

- In this (very contrived) example the `rating` column is editable but values must be between 10 and 20 (with 15 not allowed). Logic is in `adaptableOptions.ts`.
- Three server validation outcomes (each can display a message):
  - value `> 20` returns `20` — `messageType` _Warning_ and custom header
  - value `< 10` returns `10` — no `messageType` (defaults to _Info_)
  - value exactly `15` is rejected — `messageType` _Error_ and custom header
- Edits that do not break those rules, or edits outside `rating`, are left unchanged by the validator.

Demo project (Vanilla); the files without a marker are shown below:

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts
  gridOptions.ts
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts
  styles.css           [template]
index.html             [template]
package.json           [template]
tsconfig.json          [template]
```

Files marked `[template]` are the same in every demo; see the [demo template](https://www.adaptabletools.com/llms/demo-template.md#vanilla).

**`src/adaptableOptions.ts`**

```ts
import {
  AdaptableOptions,
  CellDataChangedInfo,
  ServerValidationContext,
  ServerValidationResult,
} from '@adaptabletools/adaptable';
import {Car} from './rowData';

export const adaptableOptions: AdaptableOptions<Car> = {
  primaryKey: 'model',
  adaptableId: 'Server Validation',
  editOptions: {
    validateOnServer: (serverValidationContext: ServerValidationContext) => {
      return new Promise((resolve, reject) => {
        setTimeout(
          // mimic a server check
          () =>
            resolve(
              getServerEditResponse(serverValidationContext.cellDataChangedInfo)
            ),
          1000
        );
      });
    },
  },
  initialState: {
    Theme: {CurrentTheme: 'dark'},
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'make',
            'model',
            'price',
            'firstUsed',
            'firstBought',
            'available',
            'milesToGallon',
            'rating',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
};

function getServerEditResponse(
  cellDataChangedInfo: CellDataChangedInfo
): ServerValidationResult {
  if (cellDataChangedInfo.column.columnId == 'rating') {
    if (cellDataChangedInfo.newValue == 15) {
      return {
        newCellValue: cellDataChangedInfo.oldValue,
        validationMessage: 'Cannot provide Rating of 15',
        validationHeader: 'Not Allowed',
        messageType: 'Error',
      };
    } else if (cellDataChangedInfo.newValue > 20) {
      return {
        newCellValue: 20,
        validationMessage: 'Rating cannot be greater than 20',
        validationHeader: 'Too High',
        messageType: 'Warning',
      };
    } else if (cellDataChangedInfo.newValue < 10) {
      return {
        newCellValue: 10,
        validationMessage: 'Rating cannot be less than 10',
      };
    }
  }
  return {};
}
```

**`src/columnDefs.ts`**

```ts
import {ColDef} from 'ag-grid-enterprise';
import {Car} from './rowData';

export const columnDefs: ColDef<Car>[] = [
  {
    headerName: 'Make',
    field: 'make',
    filter: true,
    editable: false,
    enableRowGroup: true,
    enablePivot: true,
    cellDataType: 'text',
  },
  {
    headerName: 'Model',
    field: 'model',
    filter: true,
    editable: false,
    cellDataType: 'text',
  },
  {
    headerName: 'Price',
    field: 'price',
    filter: true,
    editable: false,
    cellDataType: 'number',
  },
  {
    headerName: 'Rating',
    field: 'rating',
    enableValue: true,
    editable: true,
    sortable: true,
    cellDataType: 'number',
    filter: true,
    enablePivot: true,
    resizable: true,
  },
  {
    headerName: 'Miles To Gallon',
    field: 'milesToGallon',
    filter: true,
    editable: false,
    cellDataType: 'number',
    valueFormatter: (params: any) => {
      return params.value
        ? params.value.toLocaleString('en-US', {
            minimumFractionDigits: 2,
            maximumFractionDigits: 2,
          })
        : null;
    },
  },
  {
    headerName: 'First Used',
    field: 'firstUsed',
    filter: true,
    editable: false,
    cellDataType: 'date',
    valueFormatter: (params: any) => {
      return params.value
        ? new Intl.DateTimeFormat('en-GB').format(params.value)
        : '';
    },
  },
  {
    headerName: 'First Bought',
    field: 'firstBought',
    filter: true,
    editable: false,
    cellDataType: 'date',
  },
  {
    headerName: 'Available',
    field: 'available',
    filter: true,
    editable: true,
    cellDataType: 'boolean',
  },
];
```

**`src/rowData.ts`**

```ts
export interface Car {
  make: string;
  model: string;
  price: number;
  firstUsed: Date;
  firstBought: Date;
  available: boolean;
  milesToGallon: number;
  rating: number;
}

export const rowData: Car[] = [
  {
    make: 'Toyota',
    model: 'Celica',
    price: 35000,
    firstUsed: new Date(2017, 11, 4),
    firstBought: new Date(2017, 11, 4),
    available: true,
    milesToGallon: 21.345676,
    rating: 17,
  },
  {
    make: 'Toyota',
    model: 'Yaris',
    price: 40000,
    firstUsed: new Date(2013, 1, 15),
    firstBought: new Date(2013, 1, 15),
    available: true,
    milesToGallon: 29.32432423,
    rating: 14,
  },
  {
    make: 'Toyota',
    model: 'Corolla',
    price: 28000,
    firstUsed: new Date(2017, 6, 9),
    firstBought: new Date(2017, 6, 9),
    available: false,
    milesToGallon: 32.9032523473287,
    rating: 13,
  },
  {
    make: 'Ford',
    model: 'Mondeo',
    price: 32000,
    firstUsed: new Date(2009, 10, 2),
    firstBought: new Date(2009, 10, 2),
    available: true,
    milesToGallon: 28.247893473289,
    rating: 14,
  },
  {
    make: 'Ford',
    model: 'Fiesta',
    price: 35000,
    firstUsed: new Date(2018, 8, 12),
    firstBought: new Date(2018, 8, 12),
    available: false,
    milesToGallon: 34.0001,
    rating: 16,
  },
  {
    make: 'Ford',
    model: 'Focus',
    price: 26750,
    firstUsed: new Date(2017, 3, 3),
    firstBought: new Date(2017, 3, 3),
    available: false,
    milesToGallon: 31.2432432423,
    rating: 13,
  },
  {
    make: 'Ford',
    model: 'Galaxy',
    price: 41000,
    firstUsed: new Date(2015, 4, 14),
    firstBought: new Date(2015, 4, 14),
    available: false,
    milesToGallon: 29.29432404,
    rating: 12,
  },
  {
    make: 'Porsche',
    model: 'Boxter',
    price: 72500,
    firstUsed: new Date(2016, 1, 28),
    firstBought: new Date(2016, 1, 28),
    available: true,
    milesToGallon: 32.29580292,
    rating: 20,
  },
  {
    make: 'Porsche',
    model: 'Mission',
    price: 81000,
    firstUsed: new Date(2008, 10, 7),
    firstBought: new Date(2008, 10, 7),
    available: false,
    milesToGallon: 35.7822957,
    rating: 18,
  },
  {
    make: 'Mitsubbishi',
    model: 'Outlander',
    price: 97800,
    firstUsed: new Date(2017, 11, 14),
    firstBought: new Date(2017, 11, 14),
    available: true,
    milesToGallon: 19.224309,
    rating: 17,
  },
];
```

**`src/gridOptions.ts`**

```ts
import {GridOptions, themeBalham} from 'ag-grid-enterprise';

import {columnDefs} from './columnDefs';
import {rowData, Car} from './rowData';

export const gridOptions: GridOptions<Car> = {
  theme: themeBalham,
  defaultColDef: {
    resizable: true,
    sortable: true,
    editable: true,
    filter: true,
    floatingFilter: true,
  },
  columnDefs: columnDefs,
  rowData: rowData,
  sideBar: true,
  suppressMenuHide: true,
  cellSelection: true,
  statusBar: {
    statusPanels: [
      {statusPanel: 'agTotalRowCountComponent', align: 'left'},
      {statusPanel: 'agFilteredRowCountComponent'},
      {
        key: 'Center Panel',
        statusPanel: 'AdaptableStatusPanel',
        align: 'center',
      },
    ],
  },
};
```
