Pages

Monday, March 25, 2013

JQuery validation for text boxes in MVC 4

This article is about validating a MVC4 Razor text box using JQuery while entering the text in to text box. The below text box will show red color background if the entered text is not in the desired format.

My requirement is that the value entered should be 0 to 99.999 only.


It will show error if the entered text is not in the given format.



Please follow the below steps to validate your text box.

You have to add a class to the text box.

@Html.TextBoxFor(p => p._samplebox, new { @class = "validtextbox" })

and include the below code:


//function to validate the text boxes

  $(document).ready(function () {
            $(".validtextbox").forceNumeric();
            $(".validtextbox").attr('maxlength', '6');

            $('.validtextbox').keyup(function () {          
                var filter = /^[0-9]?[0-9]?(\.[0-9][0-9]?[0-9]?)?$/
                if (filter.test(this.value)) {
                    $(this).css('background-color', '#ffffff');
                }
                else {
                    $(this).css('background-color', '#EABEC1');                  
                }
            });
        });
     
        // forceNumeric() plug-in implementation
        jQuery.fn.forceNumeric = function () {

            return this.each(function () {
                $(this).keydown(function (e) {
                    var key = e.which || e.keyCode;

                    if (!e.shiftKey && !e.altKey && !e.ctrlKey && // numbers
                        key >= 48 && key <= 57 || // Numeric keypad
                        key >= 96 && key <= 105 || // comma, period and minus, . on keypad
                        key == 190 || key == 188 || key == 109 || key == 110 || // Backspace and Tab and Enter
                        key == 8 || key == 9 || key == 13 || // Home and End
                        key == 35 || key == 36 || // left and right arrows
                        key == 37 || key == 39 || // Del and Ins
                        key == 46 || key == 45)  return true;

                    return false;
                });
            });
        }

Happy coding :)


     


No comments: