DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • AI and Cybersecurity Protecting Against Emerging Threats
  • Knowing and Valuing Apache Kafka’s ISR (In-Sync Replicas)
  • Strategies for Reducing Total Cost of Ownership (TCO) For Integration Solutions
  • Integrating AWS With Salesforce Using Terraform

Trending

  • AI and Cybersecurity Protecting Against Emerging Threats
  • Knowing and Valuing Apache Kafka’s ISR (In-Sync Replicas)
  • Strategies for Reducing Total Cost of Ownership (TCO) For Integration Solutions
  • Integrating AWS With Salesforce Using Terraform

Knockout.js Validations With and Without a Plugin

Learn how to use Knockout.js to implement validations while using a Knockout.js plugin, or without the use of such a plugin.

Sibeesh Venu user avatar by
Sibeesh Venu
·
May. 11, 17 · Tutorial
Like (15)
Save
Tweet
Share
9.64K Views

Join the DZone community and get the full member experience.

Join For Free

here we are going to see how we can implement some basic validations using knockout.js . as we mentioned in the headline, we are going to create validation demos in two manners.

  • without using any plugins, our own custom way.
  • using an existing plugin, the easy way.

if you are totally new to knockout.js, i strongly recommend you read my previous post here , where i have shared some basics of knockout.js. we will be using visual studio for our development. i hope you will like this. now let’s begin.

download source code

  • knockout.js validations
  • create an html page

    to work with knockout.js, we need a page, right? let’s create it first. before we do that, please do not forget to install knockout.js and jquery from nuget.

    image title


    <!doctype html>
    <html>
    <head>
        <title></title>
        <meta charset="utf-8" />
    </head>
    <body>
    </body>
    </html>


    now create a javascipt file and include it in your page.

     <script src="validations-without-plugin.js"></script> 


    knockout.js validation without using a plugin

    open your js file (validations-without-plugin.js), this is where we are going to write our scripts. as a first step, we need to create our view model and bind it using tje applybindings function.

    $(function () {
        function myviewmodel(firstname, lastname, email) {
            this.txtfirstname = ko.observable(firstname);
            this.txtlastname = ko.observable(lastname);
            this.txtemail = ko.observable(email);
        };
        ko.applybindings(new myviewmodel("sibeesh", "venu", "sibikv4u@gmail.com"));
    });


    now, let's create our view.

    <!doctype html>
    <html>
    <head>
        <title>knockout js validations</title>
        <meta charset="utf-8" />
        <script src="scripts/jquery-3.1.1.min.js"></script>
        <script src="scripts/knockout-3.4.1.js"></script>
        <script src="scripts/validations-without-plugin.js"></script>
    
    </head>
    <body>
        <table>
            <caption>knockout js validation</caption>
            <tr>
                <td>
                    first name: <input type="text" id="txtfirstname" name="txtfirstname" data-bind='value: txtfirstname' />
                </td>
            </tr>
            <tr>
                <td>
                    last name: <input type="text" id="txtlastname" name="txtlastname" data-bind='value: txtlastname' />
                </td>
            </tr>
            <tr>
                <td>
                    email: <input type="text" id="txtemail" name="txtemail" data-bind='value: txtemail' />
                </td>
            </tr>
            <tr>
                <td>
                    <input type="button" value="submit" />
                </td>
            </tr>
        </table>
    </body>
    </html>


    if you run your page, you can see the view has been updated with the values we have given in our view model (do you remember the use of observable() ?)

    image title

    so far everything is good. now it is time to update our view model and create some extenders.

    knockout.js extenders are the easy way to give some additional functionalities to your observables. it can be anything, in this case we are going to create some validations for our observables or our controls.

    we can create the extenders and update the view as follows:

    $(function () {
        ko.extenders.isrequired = function (elm, custommessage) {
    
            //add some sub-observables to our observable
            elm.haserror = ko.observable();
            elm.message = ko.observable();
    
            //this is the function to validate the value entered in the text boxes
    
            function validatevalueentered(valentered) {
                elm.haserror(valentered ? false : true);
                //if the custom message is not given, the default one is taken
                elm.message(valentered ? "" : custommessage || "i am required �� ");
            }
    
            //call the validation function for the initial validation
            validatevalueentered(elm());
    
            //validate the value whenever there is a change in value
            elm.subscribe(validatevalueentered);
    
            return elm;
        };
    
        ko.extenders.isemail = function (elm, custommessage) {
    
            //add some sub-observables to our observable
            elm.haserror = ko.observable();
            elm.message = ko.observable();
    
            //this is the function to validate the value entered in the text boxes
    
            function validateemail(valentered) {
                var emailpattern = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-za-z\-0-9]+\.)+[a-za-z]{2,}))$/;
                //if the value entered is a valid mail id, return fals or return true
                elm.haserror((emailpattern.test(valentered) === false) ? true : false);
                //if not a valid mail id, return custom message
                elm.message((emailpattern.test(valentered) === true) ? "" : custommessage);
            }
    
            //call the validation function for the initial validation
            validateemail(elm());
    
            //validate the value whenever there is a change in value
            elm.subscribe(validateemail);
    
            return elm;
        };
    
        function myviewmodel(firstname, lastname, email) {
            this.txtfirstname = ko.observable(firstname).extend({ isrequired: "you missed first name" });
            this.txtlastname = ko.observable(lastname).extend({ isrequired: "" });
            this.txtemail = ko.observable(email).extend({ isemail: "not a valid mail id" });
        };
        ko.applybindings(new myviewmodel("sibeesh", "venu", "sibikv4u@gmail.com"));
    });


    here .extend({ isrequired: “you missed first name” }); is used for calling the extenders we just created. the first parameter is the extender name you are creating, and the second one is just a custom message. i had explained the codes with comments, if you have any issues or doubts, please feel free to pose your queries. now it is time to update our view.

    <!doctype html>
    <html>
    <head>
        <title>knockout js validations</title>
        <meta charset="utf-8" />
        <script src="scripts/jquery-3.1.1.min.js"></script>
        <script src="scripts/knockout-3.4.1.js"></script>
        <script src="scripts/validations-without-plugin.js"></script>
        <style>
            .error {
                color: #d8000c;
                background-color: #ffbaba;
                font-family: cursive;
            }
            table {
                border: 1px solid #c71585;
                padding: 20px;
            }
            td {
                border: 1px solid #ccc;
                padding: 20px;
            }
        </style>
    </head>
    <body>
        <table>
            <caption>knockout js validation</caption>
            <tr>
                <td>
                    first name: <input type="text" id="txtfirstname" name="txtfirstname" data-bind='value: txtfirstname, valueupdate: "afterkeydown"' />
                    <span class="error" data-bind='visible: txtfirstname.haserror, text: txtfirstname.message'></span>
                </td>
            </tr>
            <tr>
                <td>
                    last name: <input type="text" id="txtlastname" name="txtlastname" data-bind='value: txtlastname, valueupdate: "afterkeydown"' />
                    <span class="error" data-bind='visible: txtlastname.haserror, text: txtlastname.message'></span>
                </td>
            </tr>
            <tr>
                <td>
                    email: <input type="text" id="txtemail" name="txtemail" data-bind='value: txtemail, valueupdate: "afterkeydown"' />
                    <span class="error" data-bind='visible: txtemail.haserror, text: txtemail.message'></span>
                </td>
            </tr>
            <tr>
                <td>
                    <input type="button" value="submit" />
                </td>
            </tr>
        </table>
    </body>
    </html>


    every observable will have their own haserror and message properties. and have you noticed that we are usig valueupdate: “afterkeydown” in each data-bind event of our control? this is for initiating validation. now let’s run our application and see whether it is working fine or not.

    image title

    knockout.js validation using a plugin: the easy way

    as we are going to use a plugin, we need to install it from the nuget first. you can always get the plugin from here .

    image title

    can we create our view model now?

    $(function () {
        function myviewmodel(firstname, lastname, email) {
            this.txtfirstname = ko.observable(firstname).extend({ required: true });
            this.txtlastname = ko.observable(lastname).extend({ required: false });
            this.txtemail = ko.observable(email).extend({ email: true });
        };
        ko.applybindings(new myviewmodel("sibeesh", "venu", "sibikv4u@gmail.com"));
    });


    you can see that, there is only few lines of code when compared to the other file one we created. now we can create our view.

    <!doctype html>
    <html>
    <head>
        <title>knockout js validations</title>
        <meta charset="utf-8" />
        <script src="scripts/jquery-3.1.1.min.js"></script>
        <script src="scripts/knockout-3.4.1.js"></script>
        <script src="scripts/knockout.validation.js"></script>
        <script src="scripts/validations-plugin.js"></script>
        <style>
            table {
                border: 1px solid #c71585;
                padding: 20px;
            }
            td {
                border: 1px solid #ccc;
                padding: 20px;
            }
        </style>
    </head>
    <body>
        <table>
            <caption>knockout js validation</caption>
            <tr>
                <td>
                    first name: <input type="text" id="txtfirstname" name="txtfirstname" data-bind='value: txtfirstname' />
                </td>
            </tr>
            <tr>
                <td>
                    last name: <input type="text" id="txtlastname" name="txtlastname" data-bind='value: txtlastname' />
                </td>
            </tr>
            <tr>
                <td>
                    email: <input type="text" id="txtemail" name="txtemail" data-bind='value: txtemail' />
                </td>
            </tr>
            <tr>
                <td>
                    <input type="button" value="submit" />
                </td>
            </tr>
        </table>
    </body>
    </html>


    please don’t forget to include the knockout.validation.js in your page. if everything is ready, run your application and see the output.

    image title

    that’s all for today. you can always download the source code attached to see the complete code and application. happy coding!

    references

  • knockout js
  • knockout-validation plugin
  • see also

  • articles related to knockout.js
  • View model

    Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.

    Opinions expressed by DZone contributors are their own.

    Trending

    • AI and Cybersecurity Protecting Against Emerging Threats
    • Knowing and Valuing Apache Kafka’s ISR (In-Sync Replicas)
    • Strategies for Reducing Total Cost of Ownership (TCO) For Integration Solutions
    • Integrating AWS With Salesforce Using Terraform

    Comments

    Partner Resources

    X

    ABOUT US

    • About DZone
    • Send feedback
    • Careers
    • Sitemap

    ADVERTISE

    • Advertise with DZone

    CONTRIBUTE ON DZONE

    • Article Submission Guidelines
    • Become a Contributor
    • Visit the Writers' Zone

    LEGAL

    • Terms of Service
    • Privacy Policy

    CONTACT US

    • 600 Park Offices Drive
    • Suite 300
    • Durham, NC 27709
    • support@dzone.com

    Let's be friends: