我已经从jquery-ui添加了datepicker。问题是,如果用户没有从日期选择器中选择日期,他也可以在日期字段中写下他的生日。现在,我想,如果有人用错误的日期填写日期字段,该字段将自动变为空白并给他一条消息来写一个有效的日期。我怎么能这样做?
代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" href="css/jquery_ui.css">
<script src="js/jquery.js"></script>
<script src="js/jquery_ui.js"></script>
<script src="js/datepicker.js"></script>
</head>
<body>
<p>Date: <input type="text" id="datepicker" /></p>
</body>
</html>
//This is datepicker.js file
$( function() {
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: true,
yearRange: "c-200:c+200",
dateFormat: 'yy-mm-dd',
maxDate: 0
});
} );
答案 0 :(得分:0)
您可以使用JQuery验证,请参阅以下内容:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="https://jqueryvalidation.org/files/demo/site-demos.css">
<script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/jquery.validate.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.15.0/additional-methods.min.js"></script>
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form id="myform">
<p>Date: <input type="text" name="datepicker" id="datepicker" /></p>
<input type="submit" />
</form>
</body>
<script>
$( function() {
$( "#datepicker" ).datepicker({
changeMonth: true,
changeYear: true,
yearRange: "c-200:c+200",
dateFormat: 'yy-mm-dd',
maxDate: 0
});
} );
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$( "#myform" ).validate({
rules: {
datepicker: {
required: true,
date: true
}
}
})
</script>
</html>
&#13;
我希望它可以帮助你,再见。