javascript - check if a given value is a positive number or float with maximum two decimal places -


i trying implement validation check input text control should allow positive integer value or float maximum 2 decimal places.

here fiddler approaches i've tried: https://jsfiddle.net/99x50s2s/49/

html

enter price: <input type="text" id="price"/> (example: 10, 10.50. not include $ symbol.) <br/> <br/> <button type="button" id="check1">check method 1</button> (fails when value 1.00) <br/> <br/> <button type="button" id="check2">check method 2</button> (passes when value 45f) <br/> <br/> <button type="button" id="check3">check method 3</button> (passes when value -10) 

code:

var price = $('#price');  $('#check1').on('click', function(){    var val = $.trim(price.val());     var num = number(val);     if (string(num) === val && num >= 0)     {         alert('valid');     }     else     {         alert('invalid');     } });  $('#check2').on('click', function(){    var val = $.trim(price.val());     var num = number(val);      if (((typeof num === 'number') && (num % 1 === 0)) || parsefloat(val))     {         alert('valid');     }     else     {         alert('invalid');     } });  $('#check3').on('click', function(){    var val = $.trim(price.val());        if ($.isnumeric(val))     {         alert('valid');     }     else     {         alert('invalid');     } }); 

expectation:

the values should passed positive numbers , float maximum 2 decimals. (example 10, 10.50)

i looked @ various answers in stackoverflow non matched expectation. appreciated.

what looking value matches pattern, not it's value is. that, best off using regular expression. specifically, should catch value looking for:

/^\d+(\.\d{1,2})?$/ 

that says:

  • starting @ beginning of value (^)
  • match 1 or more digits (\d+)
  • followed option decimal point , 1 or 2 digits ((\.\d{1,2})?)
  • and no other characters before end of value ($)

that should enforce of rules, allowing perform single check validity, rather multiple ones.


edit: here example of how use it:

function checknumber(snum) {     var pattern = /^\d+(\.\d{1,2})?$/;     console.log(snum + " " + ((pattern.test(snum)) ? "" : "not ") + "valid."); }  checknumber("1");      // 1 valid. checknumber("-1");     // -1 not valid. checknumber("1234");   // 1234 valid. checknumber("1.");     // 1. not valid. checknumber("1.0");    // 1.0 valid. checknumber("1.12");   // 1.12 valid. checknumber("1.123");  // 1.123 not valid. 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -