![](/img/trans.png)
[英]I am trying to validate a string with a regular expression in the javascript controller?
[英]I am trying to validate a date with a regular expression in JavaScript but it is not working correctly?
我正在嘗試使用JavaScript驗證一個簡單的日期,但是無論我輸入哪個日期,它都會出現錯誤。.我確定自己可能做的有些愚蠢,但找不到解決方案。
<script type="text/javascript">
/* <![CDATA[ */
function validateDate(date) {
var dateCheck = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
if (dateCheck.test(date) == false) {
window.alert("Please enter a correct date");
}
else {
window.alert("The date was entered correctly!");
}
}
/* ]]> */
</script>
Please enter a date:
input type='text' name='date' id='date'>
input type='button' name="submitDate" id='submitDate' value='Submit' onclick="validateDate()">
我已經在jsFiddle以及rubular.com上的正則表達式中對其進行了測試 ,它們都使用格式為“ xx-xx-xxxx”的日期。 當您嘗試使用“ xx-xx-xx”之類的格式時,此操作將失敗。
示例代碼:
var dateCheck = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
if (dateCheck.test("02-03-2013") == false) {
window.alert("Please enter a correct date");
} else {
window.alert("The date was entered correctly!");
}
您嘗試檢查什么格式? 也許您想看看XDate ,它提供了一個很好的JavaScript庫來處理日期(您可以使用.valid
方法檢查日期是否有效)。
您的正則表達式似乎運行良好。 但是,您忘記了函數聲明中的date
參數,這可能是問題所在。
function validateDate(date) {
...
}
哦,好的,我看到您編輯了問題,我的理解更好。 在為輸入元素賦予name
屬性時,將引用此元素。 因此,如果要使用名為date
的輸入的值,則必須使用date.value
。
我用您的代碼並使用date.value
了一個date.value
: http : //jsfiddle.net/BssTY/
您可以添加更多詳細信息以進一步限制輸入:
^(([1-9]|[0][0-9]|[1-2][0-9]|[3][0-1])(\/|\-)([1-9]|[0][1-9]|[1][0-2])(\/|\-)([1-9]{1}[0-9]{3}|[0-9]{2}))$
參見http://rubular.com/r/uTJ55LKzMK
細分正則表達式以檢查月份中的天數 :
([1-9]|[0][0-9]|[1-2][0-9]|[3][0-1])
- Single digit, eg. 1 or 2 or 3 up to 9
- OR, can be double digits leading with 0, eg. 01 or 02 or 03 up to 09
- OR, can be double digits leading with 1 or 2, eg. 10 or 11 or 22 or 23 up to 29
- OR, can be double digits leading with 3, eg. 30 or 31
正則表達式檢查月份 :
([1-9]|[0][1-9]|[1][0-2])
- Single digit, eg. 1 or 2 or 3 up to 9
- OR, can be double digits leading with 0, eg. 01 or 02 or 03 up to 09
- OR, can be double digits leading with 1, eg. 10 or 11 or 12
正則表達式檢查年份 :
([1-9]{1}[0-9]{3}|[0-9]{2})
- Four digits leading with # in range [1-9], eg. 1001 or 1100, up to 9999
- OR, can be double digits leading with # in range [0-9], eg. 00 or 01 up to 99
驗證日期不只是檢查格式,還有更多。 OP功能認為“ 30-02-2013”可以。 測試字符串的一種方法是創建一個日期對象並檢查原始對象,例如
// Format dd-mm-yyyy
function validateDate(s) {
s = s.split('-');
var d = new Date(s[2], --s[1], s[0]);
return !!d && d.getMonth() == s[1] && d.getDate() == s[0];
}
validateDate('30-02-2013'); // false
validateDate('29-02-2000'); // true
使用像這樣的簡單驗證:
validformat=/^\d{2}\/\d{2}\/\d{4}$/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.