• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 749
  • Last Modified:

Javascript to allow only decimals

OK, I'm sure this is easy for someone but I can't seem to find an answer anywhere. I have a textbox on an asp.net page. I need to make sure that anything written in that box is a decimal between 0 and 1 i.e: .110, .56, .034. Values such as -.99, 1.22, etc are not allowed, nor are alpha characters, a % sign or other non-numeric characters (except the decimal point).

Does anyone have any Javascript that validates a user suppiled input is within a certain range? BTW, I'm fine with using a .net validator control instead if someone can give me the regular expression I need for it.

Thanks in advance!  
0
BrogansMom
Asked:
BrogansMom
1 Solution
 
zvytasCommented:
The following Regex should do it:

^\.(\d+)$
0
 
leakim971PluritechnicianCommented:
when do you want to validate?

here onblur : if(isNaN(this.value)||this.value<=0||this.value>=1) this.value='';

test page : http://jsfiddle.net/zArCH/1/
0
 
ZvonkoSystems architectCommented:
In my opinion is this only "lazy" typing but not decimal: .034
Therefore this my proposal:
<... onKeyUp="if(!this.value.match(/^0?(\.\d*)?$/))this.value='0.'+this.value.replace(/\D/g,'');" >

Open in new window

0
 
BrogansMomAuthor Commented:
That was exactly the expression I needed!!!

Here's how I implemented it, in case anyone benefits by this thread:
            function DecimalCheck() {
                var cc = $get("<%=rate.ClientID %>");
                debugger;
               
                if (cc.value == '') {
                    alert('Please provide a rate');
                    return false;
                }
               
                var rex = /^\.(\d+)$/
                if (rex.test(cc.value)) {
                    return true;
                }
               
                alert('Please enter the spread amount as a decimal.');
                return false;
            }
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now