Numbers and Numeric Valiation's Reg-Expressions.

Puneet20884
Posted by Puneet20884 under JavaScript category on | Points: 40 | Views : 1047
Hi,

Hope the following code is self descriptive to you.

So not mentioning much of the details here.

Please comment one reg expressions at a time from the following and uncomment all the others
//var re = /^\d+$/; // + integers
//var re = /^-\d+$/; // - integers
//var re = /^-{0,1}\d+$/; // + or - integers
//var re = /^\d*\.{0,1}\d+$/; // + numbers
//var re = /^-\d*\.{0,1}\d+$/; // - numbers
var re = /^-{0,1}[\d]*\.{0,1}\d+$/; // + or - numbers

To see the regular expressions to be used to validate:
1) +ve numeric
2) -ve numeric
3) both +ve and -ve numeric
4) +ve numbers
5) -ve numbers
6) both +ve and -ve numbers



Please copy the code to a simple text file as save that as an html page say test.htm and then open in borwser iin order to test it.

<html>
<head>
<title>Test Puneet</title>
<script language='javascript'>
function test()
{
//var re = /^\d+$/; // + integers
//var re = /^-\d+$/; // - integers
//var re = /^-{0,1}\d+$/; // + or - integers
//var re = /^\d*\.{0,1}\d+$/; // + numbers
//var re = /^-\d*\.{0,1}\d+$/; // - numbers
var re = /^-{0,1}[\d]*\.{0,1}\d+$/; // + or - numbers

var str = document.getElementById("txtVal").value;

if (String(str).search (re) !=-1) {
alert("Successful match");
} else {
alert("No match");
}

}
</script>
<body>
<input type='text' id='txtVal'/>
<input type='button' id='txtBtn' value='Check' onclick='javascript:test()'/>
<body>


Please let me know for any kind of concern related to the same.

Comments or Responses

Login to post response