...

View Full Version : How to use varioable in reguler expression???



prajwala
10-04-2012, 01:05 PM
I have called a function with passing 2 arguments in it.i is for id and other is for number.

I want to use that number in reguler expression.

Please find below code:

<html>
<head>
<script type="text/javascript">
function checkNumber(id,num){
var elementTxt=document.getElementById(id);
var a=parseInt(num);
var re5digit='/^\d{'+num+'}$/'; //regular expression defining a 5 digit number


if(elementTxt.value!=null || elementTxt.value!=""){
if (elementTxt.value.search(re5digit)==-1 ) //if match failed
{
alert("Please enter a valid 5 digit number inside form");
//return false;
}
}
}
</script>
</head>
<body>
<input type="text" id='txt'/>
<input type="button" value="ok" onclick="checkNumber('txt',5)"/>
</body>
</html>

devnull69
10-04-2012, 02:18 PM
Your variable re5digit is of type "string" and not of type "RegExp".


var re5digit = new RegExp('/^\d{'+num+'}$/');

Philip M
10-04-2012, 02:43 PM
Regular expressions can be handy for a lot of things, but for simpler tasks they are not the most efficient way. I would suggest determining if the field is not a number and is of a certain length:-



<html>
<head>

<script type="text/javascript">

function checkNumber(id,num) {
// num is a number already so no need for parseInt(), which in any case ought to specify the radix
var elementTxt = Number(document.getElementById(id).value);
if ((isNaN(elementTxt)) || (elementTxt.toString().length != num)) {
alert ("Please enter a valid " + num + "-digit number inside form");
document.getElementById(id).value = ""; // clear the field
return false;
}
}

</script>

</head>
<body>
<input type="text" id='txt' size = "5" maxlength = "5"/>
<input type="button" value="Check It" onclick="checkNumber('txt',5)"/>

</body>
</html>

The value of a form field can never be null. Only "" (blank).

You ought to know that when posting here you are asked to help us to help you by following the posting guidelines and wrapping your code in CODE tags. This means use the octothorpe or # button on the toolbar. You can (and should) edit your previous post.





Protestors Tried To Spoil Play But Actors Succeeded - Headline in Surrey Adveriser

prajwala
10-04-2012, 02:58 PM
Hey thanks all.
It worked :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum