views:

23223

answers:

13

Any quick way to set an HTML text input (<input type=text />) to only allow numeric keystrokes(plus '.')?

+12  A: 

I've used this, it's okay

http://www.javascript-coder.com/html-form/javascript-form-validation.phtml

DrG
Very useful link, +1I will accept this solution thanks for the other suggestions below guys
J Angwenyi
+10  A: 

2 solutions:

Use a form validator (for example with jQuery validation plugin)

Do a check during the onblur (i.e. when the user leaves the field) event of the input field, with the regular expression:

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>

<input type="text" ... onblur="testField(this);"/>
romaintaz
Escape . with \.
AnthonyWJones
Interestingly, I had to give the regex is "^\\d\\.?\\d*$", but that might be because the page is run through an XSLT transform.
Paul Tomblin
A: 

You may try using the '''onkeydown''' event and cancel the event (event.preventDefault or something like that) when it's not one of the allowed keys.

GoodEnough
A: 

You can attach to the key down event and then filter keys according to what you need, for example:

<input id="FIELD_ID" name="FIELD_ID" onkeypress="return validateNUM(event,this);"  type="text">

And the actual javascript handler would be:

function validateNUM(e,field)
{
    var key = getKeyEvent(e)
    if (specialKey(key)) return true;
    if ((key >= 48 && key <= 57) || (key == 46)){ 
        if (key != 46)
            return true;
        else{  
            if (field.value.search(/\./) == -1 && field.value.length > 0) 
                return true;
            else 
                return false;
        }       
    }

function getKeyEvent(e){
    var keynum
    var keychar
    var numcheck
    if(window.event) // IE
        keynum = e.keyCode
    else if(e.which) // Netscape/Firefox/Opera
        keynum = e.which
    return keynum;
}
Alex Shnayder
+10  A: 

Use this DOM

<input type='text' onkeypress='validate(event)' />

And this script

function validate(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    theEvent.preventDefault();
  }
}
geowa4
german-settings on an eeepc 900. some key's for good usabiliy do not work: - backspace (keyCode: 8) - navigation key left and right (keyCode: 37, 38)copy and paste is also possible...
michl86
so modify per locale; same idea still works.
geowa4
change to **if (theEvent.preventDefault) theEvent.preventDefault();** as it's not supported by all browsers
pstanton
i know its not supported, and i don't care. setting `returnValue` to `false` is the alternative, which i do first. if `preventDefault()` throws an error, i don't care, since it's the last line in the function; no code will be skipped because of the error.
geowa4
Most people do care, having a script error show up reflects poorly on your site.
Robert Jeppesen
A: 

Remember the regional differences (Euros use periods and commas in the reverse way as Americans), plus the minus sign (or the convention of wrapping a number in parentheses to indicate negative), plus exponential notation (I'm reaching on that one).

MusiGenesis
Continental Europeans do, anyway. In the UK, and here in Ireland, we use commas and decimal points the same way you do for numbers. Indeed, I think this use of commas and decimal points is common to the entire English-speaking world.
TRiG
+3  A: 

HTML5 has <input type=number>, which sounds right for you. Currently, only Opera supports it natively, but there is a project that has a JavaScript implementation.

Ms2ger
A: 

Thanks guys this really help me!

I found the perfert one really useful for database.

function numonly(root){
    var reet = root.value;    
    var arr1=reet.length;      
    var ruut = reet.charAt(arr1-1);   
        if (reet.length > 0){   
        var regex = /[0-9]|\./;   
            if (!ruut.match(regex)){   
            var reet = reet.slice(0, -1);   
            $(root).val(reet);   
            }   
        }  
 }

Then add the eventhandler:

onkeyup="numonly(this);"
Alex Homm
+2  A: 

And one more example, which works great for me:

function validateNumber(event) {
    var key = window.event ? event.keyCode : event.which;

    if (event.keyCode == 8 || event.keyCode == 46
     || event.keyCode == 37 || event.keyCode == 39) {
        return true;
    }
    else if ( key < 48 || key > 57 ) {
        return false;
    }
    else return true;
};

Also attach to keypress event

$(document).ready(function(){
    $('[id^=edit]').keypress(validateNumber);
});

And html:

<input type="input" id="edit1" value="0" size="5" maxlength="5" />
vmaksym
this worked great for me as well, nice work
markiyanm
A: 

wow everybody sends most important information. Thanks for sharing

<html>
<head>
<script>
function IsEmpty(aTextField)
{
 if((aTextField.value.length==0) || (aTextField.value==null)) {return true;}
 else{return false;}
 }
function IsNumeric(sText)
{
 var ValidChars = "0123456789.";
 var IsNumber=true;
 var Char;
 for(i=0;i<sText.length&&IsNumber==true;i++)
 {
  Char=sText.charAt(i);
  if(ValidChars.indexOf(Char)==-1){IsNumber=false;}
  }
 return IsNumber;
 }
function ValidateForm()
{
 if(IsEmpty(document.getElementById("account_number")))
 {
  alert('You have not entered an account number')
  document.getElementById("account_number").focus();
  return false;
  }
 if(!IsNumeric(document.getElementById("account_number").value))
 {
  alert('Please enter only numbers or decimal points in the account field')
  document.getElementById("account_number").focus();
  document.getElementById("account_number").select();
  return false;
  }
 return true;
 }
</script>
</head>
<body>
<form name="form1" action="#" method="post" onsubmit="return ValidateForm()">
 Account Number: <input type="text" id="account_number" name="account_number">
 <br />
 <input type="submit" value="Submit">
</form>
</body>
</html>
marck_don
A: 

If you want to suggest to the device(maybe a mobile phone) between alpha or numeric you can use <input type="number">

Steven
A: 

I've searched long and hard for a good answer to this, and we desperately need <input type="number", but short of that, these 2 are the most concise ways I could come up with:

<input type="text" 
       onkeyup="this.value=this.value.replace(/[^\d]/,'')">

If you dislike the non-accepted character showing for a split-second before being erased, the method below is my solution. Note the numerous additional conditions, this is to avoid disabling all sorts of navigation and hotkeys. If anyone knows how to compactify this, let us know!

<input type="text" 
onkeydown="return ( event.ctrlKey || event.altKey 
                    || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false) 
                    || (95<event.keyCode && event.keyCode<106)
                    || (event.keyCode==8) || (event.keyCode==9) 
                    || (event.keyCode>34 && event.keyCode<40) 
                    || (event.keyCode==46) )">
A: 

Best for me (with jquery) http://www.itgroup.com.ph/alphanumeric/

Aurelien