javascript - validate input with decimal precision and scale -


i trying create javascript function called on keypress event on input following:

  • input should valid decimal format (5,2) => (xxxxx.yy) variable function. input restricted if user adds value not conform format above.
  • if existing input starts . append 0 starting automatically

html

<input type="text" onkeypress="return checkdecimal(event, this, 5, 2);"  id="price2" value="27.15"> 

javascript

function checkdecimal(evt, item, lenbeforedecimal, lenafterdecimal) {     var charcode = evt.which;      var trimmed = $(item).val().replace(/\b^0+/g, "");     if(checkstartswith(trimmed, '.') == true){         trimmed = '0' + trimmed;     }      //allow following keys     //8 = backspace, 9 = tab     if(charcode == 8 || charcode == 9){         return true;     }      //only single '.' allowed     if(charcode == 46){         var dotoccurrences = (trimmed.match(/\./g) || []).length;          if(dotoccurrences != undefined && dotoccurrences == 1){             return false;         }else{             return true;         }     }      if (charcode > 31 && ((charcode < 48) || (charcode > 57))) {         return false;     }     if ($(item).val() != trimmed){         $(item).val(trimmed);}       //check start , end length     if(trimmed.indexof('.') == -1){         if(trimmed.length >= parseint(lenbeforedecimal)){             return false;         }     }else{         var inputarr = trimmed.split(".");         if(inputarr[0].length > parseint(lenbeforedecimal) || inputarr[1].length >= parseint(lenafterdecimal)){             return false;         }     }      return true; } function checkstartswith(str, prefix){     return str.indexof(prefix) === 0; } 

issues

  • if user inputs 12345.9 , moves caret position after 5, user able add digit before decimal 123456.9 should not allowed.
  • if user inputs 1.9 , remove 1 , add 5, 5 added @ end , entered value becomes 0.95 , not 5.9

js fiddle

consider using regular expression like:

/^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/; 

that allows , including required format, returns false if number part more 5 digits or if fraction more 2 digits, e.g.:

<input type="text" onkeyup="check(this.value)"><span id="er"></span>  <script>  function check(v) {   var re = /^(\d{0,5}\.\d{0,2}|\d{0,5}|\.\d{0,2})$/;   document.getelementbyid('er').innerhtml = re.test(v); }  </script> 

you'll need separate validation final value, e.g.

/^\d{5}\.\d{2}$/.test(value); 

to make sure it's required format.

i don't understand requirement add leading 0 "." since user must enter 5 leading digits anyway (unless misunderstand question).


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -