HTML5 Date Validation

后端 未结 4 1277
难免孤独
难免孤独 2021-01-19 03:07

I\'m looking to implement validation for a mobile site, where I have two input fields and I would like the first to validate the value is no later than todays date, and the

4条回答
  •  余生分开走
    2021-01-19 04:07

    I like moment.js. It makes it easier to deal with dates and times.

    First, let's make sure a day "is before tomorrow". This will depend a bit upon what the definition of tomorrow is.

    var m = moment("26/11/2013", "MM/DD/YYYY");
    // tomorrow this time
    var t = moment().add("days", 1);
    // tomorrow start of day
    var tomorrow = moment([t.year(), t.month(), t.date()]);
    if (m.lessThan(tomorrow)) {
       // today!!! (or before)
    }
    

    Similarly, the same approach can be used for a year from now. It's likely fine enough to not care about the time component in this case, and I've slogged on another day - but if it matters (e.g. looking for the start of the day), see the previous example.

    var m = moment("26/11/2013", "MM/DD/YYYY");
    var aYearFromNow = moment().add("years", 1).add("days", 1);
    if (m.lessThan(aYearFromNow)) {
       // still less than a year!
    }
    

提交回复
热议问题