Decimal in javascript

The text box should take onli decimal values ​​in javascript. No other special characters. He should not accept ".". more than once. E.g. he should not take 6 ..... 12 Can someone help ???

+3
source share
6 answers

You can use regex:

function IsDecimal(str)
{
    mystring = str;
    if (mystring.match(/^\d+\.\d{2}$/ ) ) {
        alert("match");
    }
    else
    {
    alert("not a match");
    }
}

http://www.eggheadcafe.com/community/aspnet/3/81089/numaric-validation.aspx

+1
source

You can use the Regex.test method:

if (/\d+(\.\d{1,2})/.test(myTextboxValue)) //OK...
0
source

, , , . , .

textbox.onkeyup=textbox.onchange=function(e){
    e= window.event? event.srcElement: e.target;
    var v= e.value;
    while(v && parseFloat(v)!= v) v= v.slice(0, -1);
    e.value= v;
}
0

perhaps you want to check the form input before submitting it to the server. Here is an example:

<html>
   <head>
      <title>Form Validation</title>
      <script type="text/javascript">
         function validate(){
            var field = document.getElementById("number");
            if(field.value.match(/^\d+(\.\d*)?$/)){
               return true;
            } else {
               alert("Not a number! : "+field.value);
               return false;
            }
         }
      </script>
   </head>
   <body>
      <form action="#" method="post" onsubmit="return validate();">
         <input type="text" id="number" width="15" /><br />
         <input type="submit" value="send" />
      </form>
   </body>
</html>
0
source

I just whipped it. Is it helpful?

<html>
<head>
<script type="text/javascript">
function validNum(theField) {
  val = theField.value;
  var flt = parseFloat(val);
  document.getElementById(theField.name+'Error').innerHTML=(val == "" || Number(val)==flt)?"":val + ' is not a valid (decimal) number';
}
window.onload=function(){
  validNum(document.getElementById('num'));
}
</script>
</head>
<body>
<form>
<input type="text" name="num" id="num"
onkeyup="return validNum(this)" /> <span id="numError"></span>
</form>
</body>
</html>
0
source

Source: https://habr.com/ru/post/1742114/


All Articles