1

I need to validate my Textbox by using Javascript. The TextBox shouldn't be null and after decimal point, only two digits are allowed. It will be better if you restrict any other character except .(dot) and numbers.

lanzz
  • 42,060
  • 10
  • 89
  • 98
Kedar Nayak
  • 41
  • 1
  • 15

1 Answers1

1

Please look at the below code

<html>
<head>
<title> Regexpression Tester </title>
<script type="text/javascript">
    function Validate() {       
        var rgexp = new RegExp("^([0-9]*\.?[0-9]{1,2})$");
        var input = document.getElementById("tbNumber").value;

        if (input.match(rgexp))
            alert("Valid");
        else
            alert("Not Valid");
    }
</script>
</head>
<body>
<input type="text" id="tbNumber"/>
<input type="button" onclick="Validate()" value="Validate"/>
</body>
</html>

I think it will satisy yor need.

KiranPalode
  • 498
  • 3
  • 8
  • 23
  • If the getelementbyid returns null, you wont be able to get the value property and youll get an error here – JDandChips Sep 21 '12 at 06:15
  • I have the text box with id tbNumber in my DOM. Then how getelementbyid will return null? – KiranPalode Sep 21 '12 at 06:23
  • It's good practice to test for null. Even if its in the dom, doesn't mean it will always be there. That's my _personal_ opinion. I work in a big team on dynamic pages, either of those things could lead to the object being changed and the script generating a NULL. – JDandChips Sep 21 '12 at 07:11