Reputation: 3407
I have the following code which will allow only numbers 0-9.
But i want to allow -(hyphon) also.[- ASCII code is 45]
I tried it.. But no use.. Can you update my code?
function isNumericKey(e)
{
if (window.event) { var charCode = window.event.keyCode; }
else if (e) { var charCode = e.which; }
else { return true; }
if (charCode > 31 && (charCode < 48 || charCode > 57)) { return false; }
return true;
}
function submitMyNumber()
{
var input = document.getElementById('myInput').value;
return input.match(/^[0-9-]+$/) != null;
}
<form>
<input type="text" id="myInput" name="myInput" onkeypress="return isNumericKey(event);" /><br />
<input type="submit" id="mySubmit" name="mySubmit" value="Submit My Number" onclick="return submitMyNumber();" />
</form></pre>
Laxman Chowdary
Upvotes: 1
Views: 633
Reputation: 4191
It seems that you filter the 45 charcode
function isNumericKey(e)
{
if (window.event) { var charCode = window.event.keyCode; }
else if (e) { var charCode = e.which; }
else { return true; }
if (charCode == 45 || (charCode >= 48 && charCode <= 57)
return true;
else
return false;
}
Will work better.
Start with hyphen when you specify a range in your regular expressions.
/^[-0-9]+$/
^-- here
/^[0-9-]+$/
^--- does not work here
If you want to match a date the pattern is probably something like dd-dd-dd (but which format? ISO YYYY-MM-DD ? or something else) A more correct pattern will be.
/^\d{4}-\d{2}-\d{2}$/
Probably this one is better
/^[12]\d{3}-[01]\d-[0-3]\d$/
For the DD-MM-YYYY reverting the pattern is quite simple :
/^[0-3]\d-[01]\d-[12]\d{3}$/
Upvotes: 0
Reputation: 1406
If you want to accept 29-06-2012 i.e. 2 digits hyphen 2 digits hyphen 4 digits which is date-pattern the regular expression is [0-9]{2}-[0-9]{2}-[0-9]{4}
Upvotes: 0