我想同时检查javascript和php的值,该值应类似于此格式22.22或00.44或44或55.00。
我有以下代码。
$(function(){
// $('.pixcel_rate').keypress(function (event) {
// return isNumber(event, this)
// });
$('.pixcel_rate').keypress(function (event) {
return validateFloatKeyPress($(this).val());
});
});
// THE SCRIPT THAT CHECKS IF THE KEY PRESSED IS A NUMERIC OR DECIMAL VALUE.
function validateFloatKeyPress(evt,el) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = el.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
//just one dot (thanks ddlab)
if(number.length>1 && charCode == 46){
return false;
}
//get the carat position
var caratPos = getSelectionStart(el);
var dotPos = el.value.indexOf(".");
console.log(caratPos);
console.log(dotPos);
if( caratPos >1 && dotPos>-1 && (number[0].length > 1)){
return false;
}
if( caratPos > dotPos && dotPos>-1 && (number[1].length > 1)){
return false;
}
return true;
}
function getSelectionStart(o) {
if (o.createTextRange) {
var r = document.selection.createRange().duplicate()
r.moveEnd('character', o.value.length)
if (r.text == '') return o.value.length
return o.value.lastIndexOf(r.text)
} else return o.selectionStart
}
答案 0 :(得分:0)
答案 1 :(得分:0)
您可以使用正则表达式来实现。以下是您所需的正则表达式。 https://regex101.com/r/N5gbqs/3/
function validateFloatKeyPress(value) {
//returns null if it doesnt match the given regular expression
return value.toString().match(/^(\d{2}|\d{2}\.\d{2})$/)
}
function validateFloatKeyPress(value) {
//returns false if it doesnt match the given regular expression
return (/^(\d{2}|\d{2}\.\d{2})$/).test(value.toString())
}