0
<script type="text/javascript">    
function allowDecimal(txt) {
        var theEvent = txt.htmlEvent || window.event;
        var key = theEvent.keyCode || theEvent.which;
        key = String.fromCharCode(key);
        var regex = /^\d*[0-9](|.\d*[0-9]|)*$/;

        if (!regex.test(key)) {
            theEvent.returnValue = false;
            if (theEvent.preventDefault)
                theEvent.preventDefault();
        }
    }

<asp:TextBox ID="txt" runat="server" onkeypress="allowDecimal(this);"></asp:TextBox>

This is not allowing . to be entered so can some one help me what's wrong

3 Answers 3

1

try this regex

  <script type="text/javascript">    
   function allowDecimal(txt) {
    var theEvent = txt.htmlEvent || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode(key);
    var regex = /^\d*\.?\d*$/;

    if (!regex.test(key)) {
        theEvent.returnValue = false;
        if (theEvent.preventDefault)
            theEvent.preventDefault();
    }
}
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Allowing decimal but multiple decimal points should not allow
0

you can also write like this without any regex for only one decimal validation:

var str = "hello.world"
var str2 = str.split(".");
var validate = str2.length;
if(validate != 1){
   alert("Decimal present");
}
else{
   alert("No decimal found");
}

Comments

0
var decimal=/^[+-]?(\d+(\.\d+)?|\.\d+)$/;

This matches an (optional) sign,

folllowed by any number of digits with an optional decimal point followed by digits,

or a decimal point followed by digits.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.