# Validating Data in AdapTable

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

- AdapTable provides 3 types of validation:
  - Pre-edit validation via read-only cells
  - Post-edit client validation via Validation Alerts
  - Post-edit server validation via `validateOnServer`

Users and developers can validate AG Grid edits in **three layers**, depending on whether you block editing upfront or judge the **proposed** new value:

| Layer | Evaluates | Typical use |
| ----- | --------- | ----------- |
| [Pre-Edit Validation](https://www.adaptabletools.com/docs/handbook-validating-pre-edit/index.md) | **Current** cell / row context | Cell must not enter edit mode (for example locked rows or values) |
| [Client Validation](https://www.adaptabletools.com/docs/handbook-validating-client/index.md) | **New** value (Prevent Edit alerts) | Editable cell, but this value is not allowed; roll back immediately |
| [Server Validation](https://www.adaptabletools.com/docs/handbook-validating-server/index.md) | **New** value (async function) | Allow, revert, or substitute a value after a server or external check |

Client validation runs before server validation: `validateOnServer` is invoked only after client checks (including Prevent Edit alerts) succeed.

## Pre-editing Validation

Pre-editing validation is performed using [Read-Only](https://www.adaptabletools.com/docs/handbook-validating-pre-edit/index.md) (or editable) cells.

AdapTable prevents cells which meet the read-only rule from being edited **before** a new value can be provided.

- AdapTable evaluates whether the cell can be edited using the **existing** cell value (and row context)
- It does not evaluate the value the user is entering

See [Pre-Edit Validation](https://www.adaptabletools.com/docs/handbook-validating-pre-edit/index.md) for `isCellEditable` and styling read-only cells.

## Post-editing Client Validation

AdapTable can be configured with Validation Alerts which trigger when an edit breaks an Alert rule.

Alerts with `PreventEdit` roll the data change back automatically.

Validation Alerts can be defined at design-time in [Alert State](https://www.adaptabletools.com/docs/technical-reference-alerting/index.md), or created at run-time by users.

See [Client Validation](https://www.adaptabletools.com/docs/handbook-validating-client/index.md) and [Validation Alerts](https://www.adaptabletools.com/docs/handbook-alerting-validation/index.md).

## Post-editing Server Validation

AdapTable offers [Server Validation](https://www.adaptabletools.com/docs/handbook-validating-server/index.md) through [Edit Options](https://www.adaptabletools.com/docs/technical-reference-editing/index.md) (`validateOnServer`).

An async function receives details of the proposed edit and returns whether to allow it, revert to the old value, or apply a different value—with an optional notification.

See [Server Validation](https://www.adaptabletools.com/docs/handbook-validating-server/index.md) for `ServerValidationResult` and message options.

**Example: Data Validation**

Performing Data Validation with a Prevent Edit Alert

- This example shows all 3 types of validation (using the `language` column):
  - **Pre-editing Validation** sets all cells with the value *HTML* to be read-only
  - **Client Validation** prevents the value being changed to _Python_
  - **Server Validation** has 2 rules: (1) it disallows the value *JQuery*; (2) it changes a value of *C* to *C#*
- Configuration is in `adaptableOptions.ts`

- In the `Language` column:
  - try to change a cell with *HTML* and note it's not allowed; change a different cell to *HTML* and note the new cell is now not editable
  - change a cell to *Python* and see how it triggers a Prevent Edit Alert
  - change a cell to *JQuery* and see how it gets reverted; set it to *C* and note how it gets automatically updated to *C#*

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

```text
src/
  adaptableOptions.ts
  agGridModules.ts     [template]
  columnDefs.ts        [template]
  gridOptions.ts       [template]
  index.ts             [template]
  onAdaptableReady.ts  [template]
  rowData.ts           [template]
  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,
  CellEditableContext,
  GridCell,
  ServerValidationContext,
  ServerValidationResult,
} from '@adaptabletools/adaptable';
import {WebFramework} from './rowData';

export const adaptableOptions: AdaptableOptions<WebFramework> = {
  primaryKey: 'id',
  adaptableId: 'Data Validation',
  editOptions: {
    isCellEditable: (cellEditableContext: CellEditableContext) => {
      const gridCell: GridCell = cellEditableContext.gridCell;
      if (
        gridCell &&
        gridCell.column &&
        gridCell.column.columnId === 'language'
      ) {
        return gridCell.displayValue === 'HTML' ? false : true;
      } else {
        return cellEditableContext.defaultColDefEditableValue;
      }
    },
    validateOnServer: (serverValidationContext: ServerValidationContext) => {
      return new Promise((resolve, reject) => {
        setTimeout(
          // mimic a server check
          () =>
            resolve(
              getServerEditResponse(serverValidationContext.cellDataChangedInfo)
            ),
          1000
        );
      });
    },
  },

  initialState: {
    Dashboard: {
      Tabs: [
        {
          Name: 'Demo',
          Toolbars: ['Alert'],
        },
      ],
    },
    Theme: {CurrentTheme: 'dark'},
    Alert: {
      AlertDefinitions: [
        {
          Name: 'alert-language',
          Scope: {
            ColumnIds: ['language'],
          },
          Rule: '[language] = "Python"',
          AlertProperties: {
            PreventEdit: true,
            DisplayNotification: true,
          },
          MessageType: 'Error',
          MessageText: 'You cannot change the Language to "Python"!',
        },
      ],
    },
    Layout: {
      CurrentLayout: 'Standard Layout',
      Layouts: [
        {
          TableColumns: [
            'name',
            'language',
            'github_stars',
            'license',
            'has_projects',
            'has_pages',
            'created_at',
            'has_wiki',
            'updated_at',
            'pushed_at',
            'github_watchers',
            'week_issue_change',
          ],
          Name: 'Standard Layout',
          AutoSizeColumns: true,
        },
      ],
    },
  },
  notificationsOptions: {
    position: 'TopCenter',
  },
};
function getServerEditResponse(
  cellDataChangedInfo: CellDataChangedInfo
): ServerValidationResult {
  if (cellDataChangedInfo.column.columnId == 'language') {
    if (cellDataChangedInfo.newValue == 'JQuery') {
      return {
        newCellValue: cellDataChangedInfo.oldValue,
        validationMessage: 'Cannot provide a value of JQuery',
        validationHeader: 'No longer used',
        messageType: 'Warning',
      };
    } else if (cellDataChangedInfo.newValue == 'C') {
      return {
        newCellValue: 'C#',
        validationMessage: 'Please use C# instead of C',
        validationHeader: 'C is too hard!',
        messageType: 'Info',
      };
    }
  }
  return {};
}
```

### FAQ

**Do I need all three mechanisms?**
No. Use **pre-edit** when the cell should not be editable at all. Use **client** Prevent Edit alerts for fast feedback on invalid **new** values. Use **server** validation when the decision belongs on the server or needs async logic.

**Does pre-edit block programmatic updates?**
No. `isCellEditable` guards **user-driven** UI edits only; programmatic updates (for example ticking data) can still change the grid. See [Pre-Edit Validation](https://www.adaptabletools.com/docs/handbook-validating-pre-edit/index.md).
