The best way is to check value of input, instead of pressed key. Because there are tabs, arrows, backspace and other characters that need to be checked when You use character code.
That code check input value after user pressed a key:
$('#p_first').keyup(function(){
while(! /^(([0-9]+)((\.|,)([0-9]{0,2}))?)?$/.test($('#p_first').val())){
$('#p_first').val($('#p_first').val().slice(0, -1));
}
});
While loop remove last character until input value is valid. Regex /^(([0-9]+)((\.|,)([0-9]{0,2}))?)?$/
validate integer and float number eg. "12,12", "12.1", "12.". It is important that number "12." (dot at the end) also be valid! Otherwise user can't enter any period.
And then on submit regex check for valid float number ([0-9]{1,2})
instead of ([0-9]{0,2})
:
$('form').submit(function(e){
if(! /^([0-9]+)((\.|,)([0-9]{1,2}))?$/.test($('#p_first').val())){
$('#p_first').addClass('error');
e.preventDefault();
}
});
Notice: It is better to assign $('#p_first')
into variable. var input = $('#p_first');