javascript中的日期验证器

时间:2018-04-30 08:55:30

标签: javascript

我有几个月的java经验,但现在我正在尝试编写我的第一个javascript来验证日期输入。我不确定代码中有什么问题。

            <label for="Start-date" class="label">Available start date</label>
            <input type="text" onsubmit="isValidDate()" class="w-input" maxlength="256" name="Start-date" data-name="Start date" placeholder="dd/mm/yyyy" id="Start-date" th:value="${possibleStartDate}" />
            <script>
            var validDate = true;
            function isValidDate(){

                var dateString = document.getElementById("Start-date");
                // First check for the pattern
                if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString)){
                    validDate = false;
                    return;
                }  

                // Parse the date parts to integers
                var parts = dateString.split("/");
                var day = parseInt(parts[1], 10);
                var month = parseInt(parts[0], 10);
                var year = parseInt(parts[2], 10);

                // Check the ranges of month and year
                if(year < 1000 || year > 3000 || month == 0 || month > 12){
                    validDate = false;
                    return;
                }    

                var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];

                // Adjust for leap years
                if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)){
                    monthLength[1] = 29;
                }    

                // Check the range of the day
               if (!(day > 0 && day <= monthLength[month - 1])){
                   validDate = false;
                   return;
               }else{
                   return;
               }
            };
            if(!validDate){
                alert("Invalid date!");
            }
            </script>

还有什么更好的警报替代方案?类似于文本字段下的红色小消息,按下提交按钮时输入不正确。我知道为javascript设置单独的文件会更好,但我不确定html中的哪个位置会将标记用于链接文件。

2 个答案:

答案 0 :(得分:1)

有很多事情需要一些调整:

  1. var dateString = document.getElementById("Start-date")应为var dateString = document.getElementById("Start-date").value;

  2. var day = parseInt(parts[1], 10);应为var day = parseInt(parts[0], 10);var month = parseInt(parts[0], 10);应为var month = parseInt(parts[1], 10);以支持dd/mm/yyyy

  3. 输入不会触发onsubmit,除非它们是表单的一部分,您可以尝试onblur

  4. 我已经用div包含输入,子项指示成功/错误以更好地显示消息。 (使用根div和支持样式上的类隐藏消息)

  5. 我已经完成了DOM操作中日期字符串的验证,因此您可以在多个地方重复使用验证

  6. 注意:

    1. 您可能最好将输入类型设置为date(如果支持,浏览器会打开日期选择器)
    2. 您还可以选择使用momentjs等库来简化日常操作。
    3. &#13;
      &#13;
      /**
       * Function which takes a string as an input and validates if it
       * is a date in the dd/mm/yyyy format
       * @param {string} dateString - The string representation of the date to validate
       8 @returns {boolean} value indicating if the date is valid (true) or not (false)
       */
      function isValidDate(dateString) {
        var validDate = true;
        
        // First check for the pattern
        if (!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString)) {
          return false;
        }
      
        // Parse the date parts to integers
        var parts = dateString.split("/");
        var day = parseInt(parts[0], 10);
        var month = parseInt(parts[1], 10);
        var year = parseInt(parts[2], 10);
      
        if(isNaN(day)  || isNaN(month) || isNaN(year)){
          return false;
        }
        
        // Check the ranges of month and year
        if (year < 1000 || year > 3000 || month < 1 || month > 12) {
          return false;
        }
      
        var monthLength = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      
        // Adjust for leap years
        if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
          monthLength[1] = 29;
        }
      
        // Check the range of the day
        if (!(day > 0 && day <= monthLength[month - 1])) {
          return false;
        }
        
        return true;
      
      };
      
      
      /**
       * Function which executes each time the input loses focus (onblur)
       */
      function validateDate() {
        // Get a reference to the container
        var container = document.querySelector('.date');
      
        // Clear stale error/success messages
        container.className = container.className.replace('success', '');
        container.className = container.className.replace('error', '');
      
        // Get current value of input
        var dateString = document.getElementById("Start-date").value;
        
        // Test if the string is a valid date
        var isValid = isValidDate(dateString);
        
        // Update classess of container to show success/error
        if (!isValid) {
          container.className += ' error';
        } else {
          container.className += ' success';
        }
      }
      &#13;
      div.date .error {
        display: none;
        background: red;
        color: white;
      }
      
      div.date .success {
        display: none;
        background: darkgreen;
        color: white;
      }
      
      div.date.success .success {
        display: block;
      }
      
      div.date.error .error {
        display: block;
      }
      &#13;
      <div class="date">
        <label for="Start-date" class="label">Available start date</label>
        <input type="text" onblur="validateDate()" class="w-input" maxlength="256" name="Start-date" data-name="Start date" placeholder="dd/mm/yyyy" id="Start-date" th:value="${possibleStartDate}" />
        <div class="error">Please enter a valid date</div>
        <div class="success">Date is valid</div>
      </div>
      &#13;
      &#13;
      &#13;

答案 1 :(得分:0)

如果您正在使用EcmaScript Date Time String Format,则可以使用Date构造函数。 (Info

var dateString = document.getElementById("Start-date").value;
var validDate = !(isNaN( new Date(dateString) )

HTML5还支持type="date"代码中的<input>。如果日期无效,这将阻止浏览器提交表单。

另外,我认为你的意思是

var dateString = document.getElementById("Start-date").value;

而不是

var dateString = document.getElementById("Start-date");

因为document.getElementById("Start-date")是一个对象。