我想验证jquery函数接收的某个字符串。
这是我到目前为止所做的事情
var duration=$('#duration').val();
if(//string validation?) {
$('.alert-box').html('Please use the correct format');
}
我想要的字符串格式是mm:ss(持续时间m表示分钟,s表示秒数)所以如果用户只输入m:ss或mm:s,或者如果用户输入一位数分钟或秒,它应该在零之前,如果它是9:00那么它应该是09:00。
这是我尝试的最新代码,但仍未验证
$('#btnAddTestCat').click(function () {
var code = "addTestCat";
var test_cat=$('#test_cat').val();
var duration=$('#duration').val();
var sub_cat=$('#sub_cat').val();
var e = $('.alert-box');
e.slideUp(300);
if(!(/[0-5][0-9]:[0-5][0-9]/g).test(duration)){
e.html('Please use the correct format!');
return false;
}
var dataString = 'test_cat=' + test_cat + '&duration=' + duration + '&sub_cat=' + sub_cat + '&code=' + code;
$.ajax({
type: "POST",
url: "controller/category_controller.php",
data: dataString,
cache: false,
success: function(result){
var result = $.trim(result);
if(result=='success'){
e.removeClass("alert");
e.addClass("info");
e.html('Category added!');
e.slideDown(300);
e.delay(500).slideUp(300);
}else{
e.removeClass("info");
e.addClass("alert");
e.html(result);
e.slideDown(300);
e.delay(500).slideUp(300);
}
}
});
});
答案 0 :(得分:5)
使用此正则表达式:mm:ss
if(!(/^(?:[0-5][0-9]):[0-5][0-9]$/).test(duration)){
$('.alert-box').html('Please use the correct format');
}
答案 1 :(得分:1)
<!DOCTYPE html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
<title>Test</title>
<script src="/script/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
$('#Submit').click(function(){
var val = $('#Input').val();
var validinput = true;
if(val.length!=5){
validinput = false;
}
for(var i=1; i<=val.length; i++){
if(i!=3 && !(isNumeric(val.substring(i-1,i)))){
validinput = false;
}else if(i==3 && val.substring(i-1,i)!=':'){
validinput = false;
}
}
if (!validinput){
alert(val+" does not match the format mm:ss. Please correct this issue before submitting the form.");
return false;
}else{
alert("It's correct!!");
}
});
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
});
</script>
</head>
<body>
<input type="text" id="Input" value="" /> Format = mm:ss
<br />
<button type="button" id="Submit">Submit</button>
</body>
</html>