Introduction
In this article, we will see how we can implement validation rules with knockout.js library. Client-Side validation improves the performance and helps us to validate the data before saving it into the database.
As I mentioned, in this demo, we will show a form with different fields, where we are applying the validation rules. I hope, you will like this.
Let’s start.
Create your Application
Open Visual Studio and select File-> click New Project.
The New Project Window will pop up. Select ASP.NET Web Application (.NET Framework), name your project, and click OK.
Now, a new dialog will pop up to select the template. We are going to choose MVC and click OK.
Knockout part
First of all, we are installing a knockout.js library. For doing this, right-click on References > Manage NuGet Packages.
Now, type Knockout.js in the search text box, select the first line, as shown below, and click the Install button.
After installing Knockout.js library from Solution Explorer, make sure that JS files given below have been added, as shown below.
Create HTML page
Now, we need to add new HTML page. To do this, right click on Project > Add > HTML page.
EmployeeForm.html
- <!DOCTYPE html>
- <html>
-
- <head>
- <title>.: Validation Form :.</title>
- <meta charset="utf-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <!--CSS-->
- <link href="Content/bootstrap.min.css" rel="stylesheet" />
- <style type="text/css">
- .errorStyle {
-
- background-color: #ffd800;
- color: #808080;
- font-size: 13px;
- padding: 5px 5px;
- border-radius: 5px;
- margin-top: 7px;
- }
- </style>
- </head>
-
- <body>
- <nav class="navbar navbar-default navbar-fixed-top">
- <div class="container-fluid">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
- <span class="sr-only">Toggle navigation</span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- <a class="navbar-brand" href="#">Validation With KnockOut JS</a>
- </div> <!-- END HEADER NAV -->
- </div> <!-- END CONTAINER -->
- </nav><!-- END NAV-->
- <div class="container" style="margin-top: 7%;">
- <div class="row">
- <div class="col-md-8">
- <div class="panel panel-default">
- <div class="panel-heading">
- <b> Employee Form</b>
- </div> <!-- END HEADING-->
- <div class="panel-body">
- <form>
- <div class="form-group">
- <label for="FirstName">First Name</label>
- <input type="text" id="FirstName" class="form-control" data-bind="value:FirstName" placeholder="First Name" />
- </div><!-- END FIRST NAME -->
- <div class="form-group">
- <label for="LastName">Last Name</label>
- <input type="text" id="LastName" class="form-control" data-bind="value:LastName" placeholder="Last Name" />
- </div><!-- END Last Name -->
- <div class="form-group">
- <label for="Email">Email</label>
- <input type="text" id="Email" class="form-control" data-bind="value:Email" placeholder="Email" />
- </div><!-- END Email -->
- <div class="form-group">
- <label for="Country">Country</label>
- <select class="form-control" data-bind="options: CountryList, value: Country, optionsCaption:'Choose your country ...'"></select>
- </div> <!-- END COUNTRY -->
- <div class="form-group">
- <label for="PhoneNumber">Phone Number</label>
- <input type="text" id="PhoneNumber" class="form-control" data-bind="value:PhoneNumber" placeholder="Phone Number" />
- </div><!-- END Phone Number -->
- <div class="form-group">
- <label for="Address">Address</label>
- <input type="text" id="Address" class="form-control" data-bind="value:Address" placeholder="Address" />
- </div><!-- END Address -->
- <div class="form-group">
- <label for="Password">Password</label>
- <input type="password" id="Password" class="form-control" data-bind="value:Password" placeholder="Password" />
- </div><!-- END Password -->
- <div class="form-group">
- <label for="Password">Confirm Password</label>
- <input type="password" id="ConfirmPassword" class="form-control" data-bind="value:ConfirmPassword" placeholder="ConfirmPassword" />
- </div><!-- END Confirm Password -->
- <div class="form-group">
- <label for="captcha">20 + 30</label>
- <input type="text" id="captcha" class="form-control" data-bind="value:captcha" placeholder="Captcha" />
- </div><!-- END CAPTCHA -->
- <button type="button" class="btn btn-success" data-bind="click:submit">
- <span class="glyphicon glyphicon glyphicon-floppy-disk" aria-hidden="true"></span> Save
- </button>
- <button type="button" class="btn btn-info">
- <span class="glyphicon glyphicon glyphicon-refresh" aria-hidden="true"></span> Reset
- </button>
- <div class="alert alert-success" role="alert" style="display:none; margin-top: 10px;"> <span class="glyphicon glyphicon glyphicon-ok-circle" aria-hidden="true"></span> Form has submitted with successful </div>
- <div class="alert alert-danger" role="alert" style="display:none; margin-top: 10px;"> <span class="glyphicon glyphicon glyphicon-remove-circle" aria-hidden="true"></span> Please check your submission </div>
- </form> <!-- END FORM-->
- </div> <!-- END BODY-->
- </div> <!-- END PANEL-->
- </div> <!-- END COL-MD-8-->
- </div> <!-- END ROW-->
- </div> <!-- END CONTAINER-->
- <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <!-- Include all compiled plugins (below), or include individual files as needed -->
- <script src="Scripts/bootstrap.min.js"></script>
- <!--KnockOutJs librairies-->
- <script src="Scripts/knockout-2.3.0.js"></script>
- <script src="Scripts/knockout.validation.js"></script>
- <script type="text/javascript">
- $(document).ready(function() {
-
- ko.validation.init({
-
- registerExtenders: true,
- messagesOnModified: true,
- insertMessages: true,
- parseInputAttributes: true,
- errorClass: 'errorStyle',
- messageTemplate: null
-
- }, true);
-
-
- var captcha = function(val) {
- return val == 50;
- }
-
-
- var checkPassword = function(val, other) {
- return val == other;
- }
-
- var viewModel = {
-
-
-
- FirstName: ko.observable().extend({ required: true, minLength: 2, maxLength: 17 }),
- LastName: ko.observable().extend({ required: true, minLength: 2, maxLength: 17 }),
- Email: ko.observable().extend({ email: true }),
- CountryList: ko.observableArray(['Morocco', 'India', 'USA']),
- Country: ko.observable().extend({ required: true }),
- PhoneNumber: ko.observable().extend({
- required: true,
- pattern: {
- message: 'Phone Number does not match my pattern',
- params: '^06-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}$'
- }
- }),
- Address: ko.observable().extend({ required: true }),
- Password: ko.observable().extend({ required: true }),
- captcha: ko.observable().extend({
-
-
- validation: {
- validator: captcha,
- message: 'Please check your captcha !!'
- }
- }),
- submit: function() {
- $('div.alert-success').hide();
- $('div.alert-danger').hide();
- if (viewModel.errors().length === 0) {
-
- $('div.alert-success').show();
- } else {
-
- $('div.alert-danger').show();
- }
-
- }
- };
-
-
- viewModel.ConfirmPassword = ko.observable().extend({
-
- validation: {
- validator: checkPassword,
- message: 'Please check your password !',
- params: viewModel.Password
- }
-
- })
-
- viewModel.errors = ko.validation.group(viewModel);
- ko.applyBindings(viewModel);
- });
- </script>
- </body>
-
- </html>
Adding validation to an observable
In order to apply the validation rules, we have used extenders but before we proceed, please make sure that you have added the libraries given below in your HTML page.
- <!--KnockOutJs librairies-->
- <script src="Scripts/knockout-2.3.0.js"></script>
- <script src="Scripts/knockout.validation.js"></script>
As you can see, ko.validation.init({ … }) function must be initialized with the options given below.
- registerExtenders: registers custom validation rules defined via ko.validation.rules.
- messagesOnModified: indicates whether the validation messages are triggered only when the properties are modified or not at all times.
- insertMessages: If true validation will insert either a <span> element or the template specified by messageTemplate after any element (e.g. <input>), which uses a KO value binding with a validated field.
- parseInputAttributes: indicates whether to assign the validation rules to your ViewModel, using HTML5 validation attributes.
- errorClass: defines CSS class assigned to both <input> and validation message elements.
CSS code
- <style type="text/css">
- .errorStyle
- {
-
- background-color:#ffd800;
- color:#808080;
- font-size:13px;
- padding:5px 5px;
- border-radius:5px;
- margin-top:7px;
- }
- </style>
The next step is that we can validate our model properties by using extend ({….}) function, as shown below.
FirstName property
We want to add an extender, which allows an observable to be marked as required and having minLength: 2 characters and maxLength: 17 characters.
- FirstName: ko.observable().extend({ required: true, minLength: 2, maxLength:17})
PhoneNumber property
Adding an extender that allows an observable to be required and Phone Number pattern, as shown below.
- PhoneNumber: ko.observable().extend({
- required: true,
- pattern: {
- message: 'Phone Number does not match my pattern',
- params: '^06-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}$'
- }
- })
Captcha property
We want to implement captcha in our Form. To do this, we need to use validation: {…} object, then we are adding two parameters, as given below.
- Validator: calls captcha function, which is already defined.
- Message: accepts the string message, which will be displayed, if the error has occurred.
-
- var captcha = function(val){
- return val == 50;
- }
-
- captcha: ko.observable().extend({
-
-
- validation:
- {
- validator: captcha,
- message: 'Please check your captcha !!'
- }
- })
ConfirmPassword property
Also, we are using the validation object, which needs the parameters given below.
- Validator: accepts a function as a parameter, which will compare the password.
- Message: accepts the string message, which will be displayed, if the error has occurred.
- params: provides the password field, which will be compared.
-
- var checkPassword = function(val, other){
- return val == other;
- }
-
- viewModel.ConfirmPassword = ko.observable().extend({
-
- validation: {
- validator: checkPassword,
- message: 'Please check your password !',
- params: viewModel.Password
- }
-
- })
Output
Now, you can run our demo by pressing F5.
Please share your feedback and queries in the comments box.