Link to home
Start Free TrialLog in
Avatar of ravindra333
ravindra333

asked on

Validate the textbox with decimal values only using javascript.

1) Asp.net textbox must take decimal values only using javascript.
2)after decimal point,it should accept  the values upto two digits only.it should not take more than two digits.
3)here you should  raise onkeypress or onkeydown javascript events to perform the validation.
4)the javascript code should work on both IE and Mozilla Browsers.

<script type ="text/javascript">
    function MaskMoney(evt) 
    {
    if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57))) return false;
    var parts = evt.srcElement.value.split('.');
    if (parts.length > 2) return false;
    if (evt.keyCode == 46) return (parts.length == 1);
    if (parts[0].length >= 14) return false;
    if (parts.length == 2 && parts[1].length >= 2) return false;
    }
    </script>
 
 
In aspx.cs page
-----------------
 
 protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.Attributes.Add("onKeydown", "return MaskMoney(event)");
        }

Open in new window

Avatar of DropZone
DropZone
Flag of United States of America image

You may want to check out the MaskedEdit TextBox included in the AJAX ToolKit:
      http://www.asp.net/ajax/ajaxcontroltoolkit/samples/maskededit/maskededit.aspx


In any case, to answer your question, just change the keycode for the '.' to 190 and send a direct reference to the control in the function call.  The problem is that srcElement is not defined in all browsers.

The attached code works on IE6 and Firefox 3.

      -dZ.
<script type ="text/javascript">
    function MaskMoney(obj, evt) 
    {
	//alert(evt.keyCode);
    if (!(evt.keyCode == 190 || (evt.keyCode >= 48 && evt.keyCode <= 57))) return false;
    var parts = obj.value.split('.');
    if (parts.length > 2) return false;
    if (evt.keyCode == 46) return (parts.length == 1);
    if (parts[0].length >= 14) return false;
    if (parts.length == 2 && parts[1].length >= 2) return false;
    }
    </script>
 
 
<input type="text" name="foo" value="" onKeyDown="return MaskMoney(this, event);">

Open in new window

You need to fix the server-side code that sets the attribute as such:
 protected void Page_Load(object sender, EventArgs e)
        {
            TextBox1.Attributes.Add("onKeydown", "return MaskMoney(this, event)");
        }

Open in new window

Is there a limit on the total length of the number? Do you alert user when the number is invalid?
The code, as is, only checks the length of the integer and decimal parts.  It allows for 14 digits to the left of the decimal point, and 2 digits to the right.  It doesn't generate an error, but prevents the user from adding any further digits when the maximum is reached.

I did not do that, your original code already had that.  Is there anything else that you want it to do?

      -dZ.
Avatar of ravindra333
ravindra333

ASKER

This code is working fine in IE and Mozilla browser.but back space is not working.
<script type ="text/javascript">
    function MaskMoney(obj, evt) 
    {
	//alert(evt.keyCode);
    if (!(evt.keyCode == 190 || (evt.keyCode >= 48 && evt.keyCode <= 57))) return false;
    var parts = obj.value.split('.');
    if (parts.length > 2) return false;
    if (evt.keyCode == 46) return (parts.length == 1);
    if (parts[0].length >= 14) return false;
    if (parts.length == 2 && parts[1].length >= 2) return false;
    }
    </script>
 
 
<input type="text" name="foo" value="" onKeyDown="return MaskMoney(this, event);">

Open in new window

Oh! Sorry about that.  Heh,  Check out the code below.  I just added a check for keyCode  8, which is the backspace.

       -dZ.
<script type ="text/javascript">
function MaskMoney(obj, evt) {
    var parts = obj.value.split('.');
 
    if (!((evt.keyCode == 190) ||
          (evt.keyCode ==   8) ||
          (evt.keyCode >= 48 && evt.keyCode <= 57))) return false;
          
    var parts = obj.value.split('.');
    if (parts.length > 2) return false;
    if (evt.keyCode == 46) return (parts.length == 1);
    if (evt.keyCode ==  8) return (parts.length  > 0);
    if (parts[0].length >= 14) return false;
    if (parts.length == 2 && parts[1].length >= 2) return false;
}
</script>

Open in new window

Alternatively, you can use RegularExpression to check the input of the textbox as shown in the code attached. Then change your TextBox.Attribute to this:
<input type="text" name="foo" value="" onKeyDown="return MaskMoney();">

<script language="JavaScript" type="text/javascript">
    function MaskMoney()
    {
       var pattern = /^\d+(\.\d{1,2})?$/;
       var txt = document.getElementById('<%=TextBox1.ClientID%>');
       if (txt.value.match(pattern))
       {
          return true;
       }
       else
       {
          return false;
       }
    }
</script>

Open in new window

hi,this code is not working accurately.back space is working now but right-arrow and left-arrow buttons are  not working.
<script type ="text/javascript">
function MaskMoney(obj, evt) {
    var parts = obj.value.split('.');
 
    if (!((evt.keyCode == 190) ||
          (evt.keyCode ==   8) ||
          (evt.keyCode >= 48 && evt.keyCode <= 57))) return false;
          
    var parts = obj.value.split('.');
    if (parts.length > 2) return false;
    if (evt.keyCode == 46) return (parts.length == 1);
    if (evt.keyCode ==  8) return (parts.length  > 0);
    if (parts[0].length >= 14) return false;
    if (parts.length == 2 && parts[1].length >= 2) return false;
}
</script>

Open in new window

ravindra333:

The code is working exactly as you asked.  Which other keys do you want it to accept?  I was going by what your original code had, which was that it only accepted digits and the period and controlled the size of the string.  Backspace, of course, should be supported, and that was missed by mistake.

The attached code supports left-right arrows now; it has been tested with Firefox.

Perhaps it'll be easier to just mask the specific characters that you don't want.

       -dZ.
<script type ="text/javascript">
function MaskMoney(obj, evt) {
    var parts = obj.value.split('.');
 
    if (!((evt.keyCode == 190) || // period
          (evt.keyCode ==  37) || // left arrow
          (evt.keyCode ==  39) || // right arrow
          (evt.keyCode ==   8) || // backspace
          (evt.keyCode >= 48 && evt.keyCode <= 57))) return false;
          
    var parts = obj.value.split('.');
    if (parts.length > 2) return false;
    if (evt.keyCode == 46) return (parts.length == 1);
    if (evt.keyCode ==  8) return (parts.length  > 0);
    if (parts[0].length >= 14) return false;
    if (parts.length == 2 && parts[1].length >= 2) return false;
}
</script>

Open in new window

Again this code is not working accurately.after entered 2 decimal digits(i.e .12) the left arrow button is not working in both firefox and IE browsers.please check  it once.
<script type ="text/javascript">
function MaskMoney(obj, evt) {
    var parts = obj.value.split('.');
 
    if (!((evt.keyCode == 190) || // period
          (evt.keyCode ==  37) || // left arrow
          (evt.keyCode ==  39) || // right arrow
          (evt.keyCode ==   8) || // backspace
          (evt.keyCode >= 48 && evt.keyCode <= 57))) return false;
          
    var parts = obj.value.split('.');
    if (parts.length > 2) return false;
    if (evt.keyCode == 46) return (parts.length == 1);
    if (evt.keyCode ==  8) return (parts.length  > 0);
    if (parts[0].length >= 14) return false;
    if (parts.length == 2 && parts[1].length >= 2) return false;
}
</script>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of DropZone
DropZone
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank a lot.your coding is working and it's good solution.
I got another problem.i am selecting the value in the textbox,then trying to override the selected value  in the textbox,but the value is not overriding and also it's not accepting any values from keyboard.
Hum, I guess that if you have already maxed out the length of the value, it won't accept any keystrokes.  Perhaps your approach of filtering keystrokes, in retrospect, may not have been the best, as we keep finding all these exceptional cases.

I guess you could modify the event handler to detect a selection, and allow the keystrokes regardless (which will repace the selection).

I suggest you select a "Ask Related Question" on this thread to post as a new question.  I'll participate, but that way other experts can also chime in, in case they have a better approach.

      -dZ.
Hi this discussion was really useful
but i wanted in key Press event the same validations
1) Asp.net textbox must take decimal values only using javascript.
2)after decimal point,it should accept  the values upto two digits only.it should not take more than two digits.
3)here you should  raise onkeypress javascript events to perform the validation.
4)the javascript code should work on both IE and Mozilla Browsers, safari

the Code should allow entry of valid values in text box and should not key in others as mentioned above