1
votes

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

2
So you want to accept numbers with -. right? Or can you please explain what all things you want your code to acceptSaurabh
I want to display date which can allow numbers and separator -(hyphon)..Mr.Chowdary
why do you return true when you get no event? shouldn't return false ?Hachi
Hachi, This code is working fine for numbers...Mr.Chowdary

2 Answers

0
votes

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}$/
0
votes

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}