Introduction:

In this article we will explain how to validate form input controls using knockoutjs or what is extend method in knockoutjs or why use extend method in knockoutjs.

Description:

Knockout provide client-side validation by using extender. It notifying to user when that value changes of input fields (input, textarea, select).

The following demo Knockout validation  via extender

 

Example:

@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>index</title>   
    <link href="/Content/bootstrap.css" rel="stylesheet" />
    <style type="text/css">
        .errorStyle {
            background-color: rgb(245, 78, 86);
            color: #000;
            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> Customer Form</b>
                    </div> <!-- END HEADING-->
 
                    <div class="panel-body">
 
                        <form>
                            <div class="col-md-6">
                                <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>
                            <div class="col-md-6">
                                <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>
                           
                            <div class="col-md-12">
                                <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>
                                <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>
</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-3.1.1.min.js"></script>
 
    <script src="/Scripts/bootstrap.min.js"></script>
    <!--KnockOutJs librairies-->
    <script src="/Scripts/knockout-3.4.1.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);
 
            // Captcha Function
           
 
            //checkPassword Function
            var checkPassword = function (val, other) {
                return val == other;
            }
 
            var viewModel = {
 
                //var self = this;
 
                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 is not vailid.',
                        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 }),
               
                submit: function () {
                    $('div.alert-success').hide();
                    $('div.alert-danger').hide();
                    if (viewModel.errors().length=== 0) {
                        //alert('Thank you');
                        $('div.alert-success').show();
                    } else {
                        //alert('Please check your submission');
                        $('div.alert-danger').show();
                    }
 
                }
 
 
            };
 
            //Confirm Password
            viewModel.ConfirmPassword = ko.observable().extend({
 
                validation: {
                    validator: checkPassword,
                    message: 'Please check your password !',
                    params: viewModel.Password
                }
 
            })
            //Catch errors
            viewModel.errors =ko.validation.group(viewModel);
            ko.applyBindings(viewModel);
 
        });
 
 
    </script>
 
 
</body>
 
</html>

 

Adding validation to an observable

When we need to implement validation rules in an observable we should use to extenders  with following library.

   <script src="/Scripts/knockout-3.4.1.js"></script>
    <script src="/Scripts/knockout.validation.js"></script> 

 

As you can see above , 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 (<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.

When We need to add an extender, which allows an observable to be required and minLength: 2 characters and maxLength: 17 characters.

FirstName: ko.observable().extend({ required: true, minLength: 2, maxLength:17})
 

When We need to add 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 is not vailid.',
                        params: '^06-[0-9]{2}-[0-9]{2}-[0-9]{2}-[0-9]{2}$'
                    }
                })

When We need to add an extender  that allows to compare password as show below.


·         Validator : accepts 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;
            }
            Password: ko.observable().extend({required: true }),
            //ConfirmPassword
            viewModel.ConfirmPassword = ko.observable().extend({
 
                validation: {
                    validator: checkPassword,
                    message: 'Please check your password !',
                    params: viewModel.Password
                }
 
            })

Result:



0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Welcome to SQL Tutorials Point

Don't have an account? Click here to Create a new account, it takes less than a minute.