google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Hướng dẫn kiểm tra định dạng ngày tháng hợp lệ với JavaScript Trong bài viết hôm nay, jsB@nk muốn hướng dẫn bạn chi tiết cách thức để kiểm tra định dạng hợp lệ của thời điểm, thời gian bằng JavaScript. Bài viết hướng dẫn khá chi tiết, cung cấp hầu hết các trường hợp khả dĩ bạn có thể gặp đồng thời có các giải pháp đa dạng để xử lý.

Đặc biệt bài viết này chỉ dùng mã JavaScript cơ bản mà không sử dụng bất kì thư viện JavaScript nào nên bạn sẽ dễ dàng tiếp cận các ý tưởng xử lý hơn.

Xem thêm các hiệu ứng JavaScript, mã nguồn JavaScript khác về ngày tháng, thời gian nếu bạn muốn:
- Các tiện ích chọn thời gian, ngày tháng với JavaScript
- jsDatePick - Bộ chọn ngày miễn phí trên web
- JavaScript Đồng hồ đếm ngược


Nhãn: kiểm tra, định dạng ngày tháng, thời điểm, giải pháp, mã JavaScript cơ bản

Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

Modularising the code

As we've seen before, creating re-usable functions can significantly reduce the size of your JavaScript code. These functions can even be included from an external javascript file so that the browser can cache them, and so the programmer isn't always copying and pasting.

In this case, we've created a stand-alone functions which will validate a date field:

  // Original JavaScript code by Chirp Internet: www.chirp.com.au
  // Please acknowledge use of this code by including this header.

  function checkDate(field)
  {
    var allowBlank = true;
    var minYear = 1902;
    var maxYear = (new Date()).getFullYear();

    var errorMsg = "";

    // regular expression to match required date format
    re = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/;
    
    if(field.value != '') {
      if(regs = field.value.match(re)) {
        if(regs[1] < 1 || regs[1] > 31) {
          errorMsg = "Invalid value for day: " + regs[1];
        } else if(regs[2] < 1 || regs[2] > 12) {
          errorMsg = "Invalid value for month: " + regs[2];
        } else if(regs[3] < minYear || regs[3] > maxYear) {
          errorMsg = "Invalid value for year: " + regs[3] + " - must be between " + minYear + " and " + maxYear;
        }
      } else {
        errorMsg = "Invalid date format: " + field.value;
      }
    } else if(!allowBlank) {
      errorMsg = "Empty date not allowed!";
    }
    
    if(errorMsg != "") {
      alert(errorMsg);
      field.focus();
      return false;
    }
    
    return true;
  }

Note: To convert to mm/dd/yyyy (US format) just swap regs[1] and regs[2] in the above code.

We're STILL not checking that the date entered actually exists. For an idea of how that might be done read the next article Form Validation: Credit Cards and Dates.

And another function that will validate a time input:

  // Original JavaScript code by Chirp Internet: www.chirp.com.au
  // Please acknowledge use of this code by including this header.

  function checkTime(field)
  {
    var errorMsg = "";

    // regular expression to match required time format
    re = /^(\d{1,2}):(\d{2})(:00)?([ap]m)?$/;
    
    if(field.value != '') {
      if(regs = field.value.match(re)) {
        if(regs[4]) {
          // 12-hour time format with am/pm
          if(regs[1] < 1 || regs[1] > 12) {
            errorMsg = "Invalid value for hours: " + regs[1];
          }
        } else {
          // 24-hour time format
          if(regs[1] > 23) {
            errorMsg = "Invalid value for hours: " + regs[1];
          }
        }
        if(!errorMsg && regs[2] > 59) {
          errorMsg = "Invalid value for minutes: " + regs[2];
        }
      } else {
        errorMsg = "Invalid time format: " + field.value;
      }
    }

    if(errorMsg != "") {
      alert(errorMsg);
      field.focus();
      return false;
    }
    
    return true;
  }

and it's now clear to just about anyone what main validation function is doing:

  function checkForm(form)
  {
    if(!checkDate(form.startdate)) return false;
    if(!checkTime(form.starttime)) return false;
    if(!checkDate(form.enddate)) return false;
    return true;
  }

The output will be almost identical to the previous example.

We could even write the checkForm function now as:

  function checkForm(form)
  {
    return checkDate(form.startdate) && checkTime(form.starttime) && checkDate(form.enddate);
  }

Adjusting the code for different date formats

Visitors from some countries may find it confusing that we're using the dd/mm/yyyy date format instead of the American or other standards. Modifying the code to account for these differences is quite simple and involves only minor changes.

US Date Format MM/DD/YYYY

In the checkDate function above you only need to replace references to regs[1] with regs[2] and vice-versa to reflect the change in order of the day and month values.

European Format YYYY-MM-DD

In the checkDate function above you only need to change the regular expression (re) to /^(\d{4})-(\d{1,2})-(\d{1,2})/ and then replace references to regs[1] with regs[3] and vice-versa as the year and day values have now changed position.

Related Articles

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web