[英]javascript regex for score
什么是學生正則表達式,例如:12.5,99.5,87,1.66
帶有(。)的最大字符長度是5,像這樣:99.99
標記在0到100之間
我用了這個,但是沒用
var rmark = /^\d{0,1}\.|(\d{0,4})$/;
var txtS = $(":text");
for (var i = 0; i < txtS.length; i++) {
if (!rmark.test(txtS.eq(i).val())) {
er = 1; break;
}
}
由於似乎要驗證的字符串來自<input type="text">
元素,因此您可以使用HTML5驗證而不是JS驗證,然后讓瀏覽器為您完成驗證:
<input type="number" max="99.99" min="0" step=".01" />
但是,即使您需要使用JS進行驗證,仍然可以使用HTML5驗證而不是regex:
var isValid = (function() {
var el = document.createElement('input');
el.type = "number";
el.max = 99.99;
el.min = 0;
el.step = .01;
return function isValid(value) {
el.value = value;
return el.validity.valid;
};
})();
http://regex101.com/r/cX1qL4/1
/^\d{1,2}(\.\d{1,2})?$/
這意味着...
^ - from the start of the string
\d{1,2} - 1 or 2 digits
( - capture group that is not required
\. - escaped dot
\d{1,2} - 1 or 2 digits
)? - this group is not required to present in the string
$ - end of the string
ps:如果可以為空,則/^(\\d{1,2}(\\.\\d{1,2})?)?$/
pps:如果范圍是0到100,則/^(100|(\\d{1,2})(\\.\\d{1,2})?)?$/
或者您可以在此處進行測試- 運行代碼段
$(function(){ $('input').keyup(function() { var regexp = /^(100|(\\d{1,2})(\\.\\d{1,2})?)?$/; if (!regexp.test($(this).val())) $(this).addClass('bad'); else $(this).removeClass('bad'); }); });
.bad {color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script> <input type="text">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.