---
title: "Custom validation rules and validation messages in Knockout"  
description: "Custom validation rules and validation messages in Knockout"  
author: "ICSM Computer"  
published: 2025-04-23  
updated: 2025-04-23  
canonical: https://www.mindstick.com/interview/34052/custom-validation-rules-and-validation-messages-in-knockout  
category: "knockcout js"  
tags: ["knockout.js", "knockout.js data-binding"]  
reading_time: 4 minutes  

---

# Custom validation rules and validation messages in Knockout

Custom validation in **Knockout.js** is a super useful way to ensure data is correct **before** submitting a form. Let’s explore how to build **custom rules**, show **validation messages**, and enhance UX with real-time feedback.

To handle validation easily, use this Knockout plugin:

```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>
```

## Example: Custom Email Validation

### Step 1: Extend Observable with Rules

```javascript
ko.validation.init({ insertMessages: true, decorateElement: true });

function ViewModel() {
  const self = this;

  self.name = ko.observable().extend({
    required: {
      message: "Name is required."
    },
    minLength: {
      params: 3,
      message: "Name must be at least 3 characters."
    }
  });

  self.email = ko.observable().extend({
    required: true,
    email: true
  });

  self.age = ko.observable().extend({
    validation: {
      validator: function (val) {
        return val > 18;
      },
      message: "Age must be greater than 18.",
      params: 18
    }
  });

  self.errors = ko.validation.group(self);

  self.submitForm = function () {
    if (self.errors().length === 0) {
      alert("Form is valid!");
    } else {
      self.errors.showAllMessages();
    }
  };
}

ko.applyBindings(new ViewModel());
```

### Step 2: HTML Form

```html
<form data-bind="submit: submitForm">
  <div>
    <label>Name:</label>
    <input data-bind="value: name" />
  </div>

  <div>
    <label>Email:</label>
    <input data-bind="value: email" />
  </div>

  <div>
    <label>Age:</label>
    <input type="number" data-bind="value: age" />
  </div>

  <button type="submit">Submit</button>
</form>
```

You'll now get:

1. **Inline messages** like "Name is required."
2. **Automatic red borders** on invalid fields
3. Real-time updates as users type

## Built-In Rules

1. `required`
2. `min`, `max`, `minLength`, `maxLength`
3. `email`, `number`, `pattern`
4. `equal`, `notEqual`

## Creating Custom Rules Globally

You can define a custom validator rule and reuse it:

```javascript
ko.validation.rules['startsWithA'] = {
  validator: function (val) {
    return val && val.charAt(0).toLowerCase() === 'a';
  },
  message: 'The value must start with "A".'
};

ko.validation.registerExtenders();
```

Then use it:

```javascript
self.username = ko.observable().extend({ startsWithA: true });
```

#### Summary

| Feature | Description |
| --- | --- |
| `.extend({ ... })` | Attaches validation to an observable |
| `ko.validation.group()` | Gathers all errors into one group |
| `errors.showAllMessages()` | Displays all error messages manually |
| Global rules | Reusable across multiple observables |
| Decorators/messages | Automatically added to HTML for better UX |

## Answers

### Answer by ICSM Computer

Custom validation in **Knockout.js** is a super useful way to ensure data is correct **before** submitting a form. Let’s explore how to build **custom rules**, show **validation messages**, and enhance UX with real-time feedback.

To handle validation easily, use this Knockout plugin:

```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.5.1/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout-validation/2.0.3/knockout.validation.min.js"></script>
```

## Example: Custom Email Validation

### Step 1: Extend Observable with Rules

```javascript
ko.validation.init({ insertMessages: true, decorateElement: true });

function ViewModel() {
  const self = this;

  self.name = ko.observable().extend({
    required: {
      message: "Name is required."
    },
    minLength: {
      params: 3,
      message: "Name must be at least 3 characters."
    }
  });

  self.email = ko.observable().extend({
    required: true,
    email: true
  });

  self.age = ko.observable().extend({
    validation: {
      validator: function (val) {
        return val > 18;
      },
      message: "Age must be greater than 18.",
      params: 18
    }
  });

  self.errors = ko.validation.group(self);

  self.submitForm = function () {
    if (self.errors().length === 0) {
      alert("Form is valid!");
    } else {
      self.errors.showAllMessages();
    }
  };
}

ko.applyBindings(new ViewModel());
```

### Step 2: HTML Form

```html
<form data-bind="submit: submitForm">
  <div>
    <label>Name:</label>
    <input data-bind="value: name" />
  </div>

  <div>
    <label>Email:</label>
    <input data-bind="value: email" />
  </div>

  <div>
    <label>Age:</label>
    <input type="number" data-bind="value: age" />
  </div>

  <button type="submit">Submit</button>
</form>
```

You'll now get:

1. **Inline messages** like "Name is required."
2. **Automatic red borders** on invalid fields
3. Real-time updates as users type

## Built-In Rules

1. `required`
2. `min`, `max`, `minLength`, `maxLength`
3. `email`, `number`, `pattern`
4. `equal`, `notEqual`

## Creating Custom Rules Globally

You can define a custom validator rule and reuse it:

```javascript
ko.validation.rules['startsWithA'] = {
  validator: function (val) {
    return val && val.charAt(0).toLowerCase() === 'a';
  },
  message: 'The value must start with "A".'
};

ko.validation.registerExtenders();
```

Then use it:

```javascript
self.username = ko.observable().extend({ startsWithA: true });
```

#### Summary

| Feature | Description |
| --- | --- |
| `.extend({ ... })` | Attaches validation to an observable |
| `ko.validation.group()` | Gathers all errors into one group |
| `errors.showAllMessages()` | Displays all error messages manually |
| Global rules | Reusable across multiple observables |
| Decorators/messages | Automatically added to HTML for better UX |


---

Original Source: https://www.mindstick.com/interview/34052/custom-validation-rules-and-validation-messages-in-knockout

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
