JavaScript'te ondalık sayıları doğrulamanın en temiz, en etkili yolu nedir?
Bonus puan:
Test senaryoları:
01. IsNumeric('-1') => true
02. IsNumeric('-1.5') => true
03. IsNumeric('0') => true
04. IsNumeric('0.42') => true
05. IsNumeric('.42') => true
06. IsNumeric('99,999') => false
07. IsNumeric('0x89f') => false
08. IsNumeric('#abcdef') => false
09. IsNumeric('1.2.3') => false
10. IsNumeric('') => false
11. IsNumeric('blah') => false
Bu yol iyi çalışıyor gibi görünüyor:
function IsNumeric(input){
var RE = /^-{0,1}\d*\.{0,1}\d+$/;
return (RE.test(input));
}
Ve test etmek için:
// alert(TestIsNumeric());
function TestIsNumeric(){
var results = ''
results += (IsNumeric('-1')?"Pass":"Fail") + ": IsNumeric('-1') => true\n";
results += (IsNumeric('-1.5')?"Pass":"Fail") + ": IsNumeric('-1.5') => true\n";
results += (IsNumeric('0')?"Pass":"Fail") + ": IsNumeric('0') => true\n";
results += (IsNumeric('0.42')?"Pass":"Fail") + ": IsNumeric('0.42') => true\n";
results += (IsNumeric('.42')?"Pass":"Fail") + ": IsNumeric('.42') => true\n";
results += (!IsNumeric('99,999')?"Pass":"Fail") + ": IsNumeric('99,999') => false\n";
results += (!IsNumeric('0x89f')?"Pass":"Fail") + ": IsNumeric('0x89f') => false\n";
results += (!IsNumeric('#abcdef')?"Pass":"Fail") + ": IsNumeric('#abcdef') => false\n";
results += (!IsNumeric('1.2.3')?"Pass":"Fail") + ": IsNumeric('1.2.3') => false\n";
results += (!IsNumeric('')?"Pass":"Fail") + ": IsNumeric('') => false\n";
results += (!IsNumeric('blah')?"Pass":"Fail") + ": IsNumeric('blah') => false\n";
return results;
}
Bu regex'i http://www.codetoad.com/javascript/isnumeric.asp adresinden ödünç aldım. Açıklama:
/^ match beginning of string
-{0,1} optional negative sign
\d* optional digits
\.{0,1} optional decimal point
\d+ at least one digit
$/ match end of string
Şunları da eklemek isterim:
1. IsNumeric('0x89f') => true
2. IsNumeric('075') => true
Pozitif hex sayıları 0x
ile başlar ve negatif hex sayıları -0x
ile başlar.
Pozitif okt sayıları 0
ile başlar ve negatif okt sayıları -0
ile başlar.
Bu, daha önce bahsedilenlerin çoğunu dikkate alır, ancak onaltılık ve sekizlik sayıları, negatif bilimsel, Sonsuzluğu içerir ve ondalık bilimselliği kaldırmıştır (4e3.2
geçerli değildir).
function IsNumeric(input){
var RE = /^-?(0|INF|(0[1-7][0-7]*)|(0x[0-9a-fA-F]+)|((0|[1-9][0-9]*|(?=[\.,]))([\.,][0-9]+)?([eE]-?\d+)?))$/;
return (RE.test(input));
}
Eklemek istediğim birkaç test var:
IsNumeric('01.05') => false
IsNumeric('1.') => false
IsNumeric('.') => false
Bunu buldum:
function IsNumeric(input) {
return /^-?(0|[1-9]\d*|(?=\.))(\.\d+)?$/.test(input);
}
Çözüm şunları kapsar: