Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Javascript

Knockout JS Validations, Without a Plugin and Using a Plugin

5.00/5 (3 votes)
3 Mar 2017CPOL4 min read 6.1K  
Knockout JS Validations, without a Plugin and using a Plugin

Here, we are going to see how we can implement some basic validations using Knockout JS. As we mentioned in the heading, we are going to create validation demo in two ways:

  • Without using any plug in, our own custom way
  • Using an existing plug in, easy way

If you are totally new to Knockout JS, I stringly recommend you read my previous post here, where I 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.

Background

As I have been working in a project where we use Knockout JS, it was my duty to do some validation for an existing page. This article shows the ways I have tried to implement the same. Like I said above, using a plug in and without using a plug in. Now let’s go and implement the same in your application too. Shall we?

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.

Installing_KnockOut_JS_from_NuGet

Installing_KnockOut_JS_from_NuGet
HTML
<!DOCTYPE html>
<html>
<head>
    <title></title>
	<meta charset="utf-8" />
</head>
<body>
</body>
</html>

Now create a JS file and include it in your page.

JavaScript
<script src="Validations-Without-Plugin.js"></script>

Let’s Begin Our Tutorial – 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 applyBindings function. Am I right?

JavaScript
$(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:

HTML
<!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 got updated with the values we have given in our view model (Do you remember the use if observable()?)

Knockout_JS_Observables_Updated

Knockout_JS_Observables_Updated

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 preceding:

JavaScript
$(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 false 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 have 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 code with comments, if you have any issues or doubts, please feel free to ask your queries. Now it is time to update our view.

HTML
<!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 be having their own hasError and message properties. And have you noticed that we are using 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.

Knockout JS validation without a plugin demo

Knockout JS validation without a plug in demo

Knockout JS Validation Using A plug in – Easy Way

As we are going to use a plug in, we need to install it from the NuGet first. You can always get the plug in from here.

Knockout_Validation_JS_from_NuGet

Knockout_Validation_JS_from_NuGet

Can we create our view model now?

JavaScript
$(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 are only few lines of codes when compared to the old one we created. Now we can create our view.

HTML
<!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.

Knockout JS validation with plugin demo

Knockout JS validation with plug in demo

That’s all for today. You can always download the source code attached to see the complete code and application. Happy coding!

References

See Also

Conclusion

Did I miss anything that you think is needed? Could you find this post useful? I hope you liked this article. Please share your valuable suggestions and feedback.

Your Turn. What Do You Think?

A blog isn't a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you're better off posting it on C# Corner, Code Project, Stack Overflow, ASP.NET Forum instead of commenting here. Tweet or email me a link to your question there and I'll definitely try to help if I can.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)