regex - Jquery validate input to eight integers and two decimals -


i've tried code guess have error regex since it's true.

besides regex, have problem keypress since i'm testing value before adding new char, don't want use keyup since don't know last char added (the user not input char @ end of input field).

i appreciate solution, thanks.

$('.myinputfield').keypress(function(){     var val = $(this).val();     var regextest = /^[0-9]{0,8}[.][0-9]{0,2}|[0-9]{0,8}$/;     var ok = regextest.test(val);     if(ok)         return true;     else         return false; 

i think may want regex this:

/^\d{0,8}(\.\d{0,2})?$/ 

you using . instead of \., . match any character.

the ? near end allows have ".12" or not have it.

\d short-cut way of restricting digits.

please consider not using keypress - keyup (better) or change (best) other options think about.

if need "extremely responsive" feedback (can't use change), consider doing (please use better approach simple css i've used in example):

$('.myinputfield').keyup(function(e){   var val = $(this).val();   var regextest = /^\d{0,8}(\.\d{1,2})?$/;   var ok = regextest.test(val);   if(ok) {       $(this).css('background-color', 'green');   } else {       $(this).css('background-color', 'red');   } }); 

js fiddle example

note: i've changed code if enter . in input, expect put at least 1 digit following decimal. if don't want edit, change \d{1,2} \d{0,2}


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -