最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - check input value for specific format using Javascript - Stack Overflow

programmeradmin5浏览0评论

I have an input field that allows a user to enter a date.

I need this date to be in the following format: 10Jan13 (capitalization is not important)

There is a popup calender that if used will format the date correctly for the user.

I'd like to check the value of the input onblur using Javascript to be sure that the user did not either paste or type the date improperly.

I am currently checking number-only fields like this:

var numbers = /^[0-9]+$/;

if (!BIDInput.value.match(numbers))
{
    checkedInput.value = "";
    alert('Not a number');
}

and I'm checking letters-only fields like this:

var letters = /^[a-z]+$/ 

if (!nameInput.value.match(letters))
{
 nameInput.value = "";
     alert('Not a letter');
}

I would like to check the date format in a similar a fashion if possible. But anything that acplishes the task will do. Can anyone point me in the right direction on how to get this done?

I know that client side validation does not replace server side validation. This is for user experience purposes only.

I have an input field that allows a user to enter a date.

I need this date to be in the following format: 10Jan13 (capitalization is not important)

There is a popup calender that if used will format the date correctly for the user.

I'd like to check the value of the input onblur using Javascript to be sure that the user did not either paste or type the date improperly.

I am currently checking number-only fields like this:

var numbers = /^[0-9]+$/;

if (!BIDInput.value.match(numbers))
{
    checkedInput.value = "";
    alert('Not a number');
}

and I'm checking letters-only fields like this:

var letters = /^[a-z]+$/ 

if (!nameInput.value.match(letters))
{
 nameInput.value = "";
     alert('Not a letter');
}

I would like to check the date format in a similar a fashion if possible. But anything that acplishes the task will do. Can anyone point me in the right direction on how to get this done?

I know that client side validation does not replace server side validation. This is for user experience purposes only.

Share Improve this question edited May 8, 2013 at 14:02 Jon Adams 25.2k18 gold badges84 silver badges121 bronze badges asked Feb 18, 2013 at 13:03 Wesley SmithWesley Smith 19.6k22 gold badges91 silver badges134 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

You're pretty much there with what you have. Basically your format is one or two digits, then one of 12 possible strings, followed by two digits. So for instance:

var shortDateRex = /^\d{1,2}(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\d{2}$/;

Breakdown:

  • ^ Start of string.

  • \d{1,2} One or two digits.

  • (:?...) A non-capturing group. Or you could use a capture group if you like.

  • Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec An alternation, allowing any of those twelve choices. Naturally you can add more if you like. If you have two choices that start the same way (Jan and January, for instance), put the longer one earlier in the alternation.

  • \d{2} Two digits.


Side note: I'd have to remend against two-digit dates on principle, and particularly given where in the century we currently are!


Responding to Amberlamps' ment that this doesn't validate the date: Once you've validated the format, it's trivial to then check the date itself if you like (to rule out 30Feb13, for instance):

var validateDateString = (function() {
  var monthNames = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec".toLowerCase().split("|");
  var dateValidateRex = /^(\d{1,2})(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)(\d{2})$/i;
  var arbitraryCenturyCutoff = 30;

  function validateDateString(str) {
    var match;
    var day, month, year;
    var dt;

    match = dateValidateRex.exec(str);
    if (!match) {
      return false;
    }
    day   = parseInt(match[1]);
    month = monthNames.indexOf(match[2].toLowerCase()); // You may need a shim on very old browsers for Array#indexOf
    year  = parseInt(match[3], 10);
    year += year > arbitraryCenturyCutoff ? 1900 : 2000;

    dt = new Date(year, month, day);

    if (dt.getDate() !== day ||
      dt.getMonth() !== month ||
      dt.getFullYear() !== year) {
      // The input was invalid; we know because the date object
      // had to adjust something
      return false;
    }
    return true;
  }

  return validateDateString;
})();

...or something along those lines.

Live Example | Source

Or if (like me) you hate to see a list like that list of month names repeated you can use the RegExp constructor with a string instead, but you have to remember to duplicate your backslashes:

var monthNamesString = "Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec";
var monthNames = monthNamesString.toLowerCase().split("|");
var dateValidateRex = new RegExp("^(\\d{1,2})(" + monthNamesString + ")(\\d{2})$", "i");

Live Example | Source

You would use the following regular expression to check for a string starting with 2 numbers, followed by 3 characters followed by 2 numbers

[0-9]{2}[a-zA-Z]{3}[0-9]{2}
发布评论

评论列表(0)

  1. 暂无评论