I want to validate an array of objects for valid time values

123 views Asked by At

I'm trying to validate the following array of objects: [{from: '10:00', to: '16:00'}, null, {from: '09:00', to: '16:00'}, etc. ]

I want exactly 7 objects in that array, how do I validate that? I guess adding both .min(7) and .max(7) is not the best practice. How can I let NULL values through as well?

Also is this other part good or would you change something? I'm new to JavaScript.

schedule: array().of(
    object().shape({
      from: string()
        .required()
        .matches(/^(0[0-9]|1[0-9]|2[0-3]):(00|30)$/),
      to: string()
        .required()
        .matches(/^(0[0-9]|1[0-9]|2[0-3]):(00|30)$/),
    })
  ),
2

There are 2 answers

2
HoldOffHunger On BEST ANSWER

To check something as a simple time value, i.e., 12:34, you can use this regex: /^[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/. Code:

var item = '10:00';
console.log(item.match(/^[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/));

  • ^ : Indicates the start of the string.
  • [0-5]: Some character 0 to 5.
  • [0-5]{1}: Some character 0 to 5, and exactly one of these.
  • [0-9]: Some character from 0 to 9.
  • [0-9]{1}: Some character from 0 to 9, and exactly one of these.
  • [0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}: Something between 00:00 and 59:59.
  • $ : Indicates the end of the string.

I have implemented it for your data structure. Note: I added in a false value, so we could see it actually indicate invalid.

var items = [
  {from: '10:00', to: '16:00'},
  null,
  {from: '09:00', to: '16:00'},
  {from: '09:00', to: '16:001234'}
];

items.forEach((item) => {
    logstring = "Item : ";
    if(!item) {
      logstring += 'NULL/VALID';
    } else {
      logstring += item.from + " " ;
      if(item.from.match(/^[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/)) {
          logstring += 'VALID';
      } else {
          logstring += 'INVALID';
      }
      
      logstring += ', ' + item.to + " " ;
      if(item.to.match(/^[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/)) {
          logstring += 'VALID';
      } else {
          logstring += 'INVALID';
      }
    }
    console.log(logstring);
});

1
Simran On

Use validation is() property. Here is the documentation link: https://validatejs.org/#validators-length