Apply Knockout Validations in MVC Application: Part 2

Introduction

In my previous article I explained How to Apply Knockout Validations in MVC Application.

This article is a continuation of that article. In this article I will tell you about some more Knockout validations in MVC Applications.

In the previous article you saw:

  • Required Validator
  • MinValue Validator
  • MaxValue Validator
  • Email Validator

In this article I will show you:

  • Date Validator
  • Number Validator
  • Whole Number Validator
  • Phone Number for US Validator

Let's see how to apply the following validations.

Date Validation

Date Validation will check whether a Date is entered in the correct format.

All the validations are applied using the Extend Function. Date validation is also applied in the same format.

            self.Title = ko.observable("").extend({ required: true, date: true });

This validation validates both slashes and dashes for separating the days from months and years, both can be used together.

Output

knockout validation in MVC

In the output you can see that as I enter some invalid text, an error message is displayed by the TextBox.

Number Validation

Number Validation will ensure that only numbers are entered, even if you enter a non-numeric value between the numbers the validation will also detect that. It's syntax is as follows:

            self.Title = ko.observable("").extend({ required: true, number: true });

It's output will be as follows:

Output

knockout validation in MVC

You can see that even if I entered any unexpected value then it also is showing the error.

Whole Number Validation

Whole Number validation will ensure that a number is a Whole Number, if it's found to be a decimal number or not a number then it will throw an error. It's syntex is as follows:

        self.Title = ko.observable("").extend({ required: true, number: true, digit: true });

"digit: true" specifies to check for a whole number.

It's output is as follows:

Output

knockout validation in MVC

Phone Number for US Validation

This is a special type of validation that will ensure that the entered number belongs to the US or not. It's syntax is as follows:

            self.Title = ko.observable("").extend({ required: true, phoneUS: true });

Eleven digits with 1 at the start will be required to satisfy this validation.

The output is as follows:

Ouput

knockout validation in MVC

But if you enter the number in the format 1-***-***-**** then the validation will be satisfied.


Similar Articles