提交表格之前,如何验证日期格式?
我尝试执行以下操作。但是,它不起作用。
<p> Date: <br />
<input type="text" id="date" name="date">
</p>
<input type="submit" id="submit" value="Send" />
</fieldset>
</form>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
$(function() {
$('#submit').click(function() {
$.validator.addMethod(
"DateFormat",
function(value, element) {
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy";
);
// validate and process form here
$('#contact').validate({
rules :
date: {
DateFormat : true
}
});
var dataString = $('form[name="contact"]').serialize();
$.ajax({
type: "POST",
data: dataString,
url : "ajax.php",
});
});
});
</script>
最佳答案
您应该在插件之前加载jquery,如下所示:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
否则,验证插件将无法正常工作。
编辑-您的JavaScript代码中有一些错误,这是一个有效的小提琴http://jsfiddle.net/Eu8eS/1/
工作代码:
$(function() {
$('#submit').click(function() {
$.validator.addMethod(
"DateFormat",
function(value, element) {
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy"//removed ;
);
// validate and process form here
$('#contact').validate({
rules :{//added here {
date: {
DateFormat : true
}
}//added here }
});
var dataString = $('form[name="contact"]').serialize();
$.ajax({
type: "POST",
data: dataString,
url : "ajax.php",
});
});
});
关于jquery - jQuery验证日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6598386/