Node property validation function for date formatting

I am creating a new Node-RED node that requires a date using a yyyymmdd format. Has anyone created a node that implements a property validation function on date formatting? I want to filter out or rewrite "yyyy-mm-dd" or "yyyy/mm/dd" as yyyymmdd

All I have now is:

    defaults: {
        date: { value:0, validate:RED.validators.number(), required:true},
    },

I give a hint in the input

  <div class="form-row">
   <label for="node-input-date"><i class="fa fa-calendar"></i> Select Date</label>
    <input type="text" id="node-input-date" placeholder="yyyymmdd">
  </div>

Hi @johnwalicki

the validator can only be used to check if it is valid - it can't do any rewriting. You'd have to implement that part yourself.

I'd use a regex validator for this - as you need to ensure its a certain length. Something like:

validate:RED.validators.regex(/^\d{8}/)

That would do a crude check for exactly 8 digits. If you wanted to check those 8 digits represent a valid year, then you'd need a custom validator...

validate: function(v) {
   if (!/^\d{8}/.test(v)) { return false; }
   var year = v.substring(0,4);
   var month = v.substring(4,6);
   var day = v.substring(6,8);
   // Date.parse will return NaN if this isn't a valid date
   var time = Date.parse(year+"-"+month+"-"+day);
   return !isNaN(time);
}
2 Likes

Thanks Nick - Your validate function snippet is very useful and makes the node more robust in handling bad input. I've incorporated it into my new node-red-contrib node.

defaults: {
        date: { value:0, required:true, validate: function(v) {
             if (!/^\d{8}/.test(v)) { return false; }
             var year = v.substring(0,4);
             var month = v.substring(4,6);
             var day = v.substring(6,8);
             // Date.parse will return NaN if this isn't a valid date
             var time = Date.parse(year+"-"+month+"-"+day);
             return !isNaN(time);
          }
        }
 }

If you wanted to be kinder to your users, it would also be easy to implement a re-write function upon user input.

The Editor gets access to jQuery and you can attach a function of the on-blur or on-change events, check the format on the fly and re-write the input.

Great idea - will add this to the todo list. Want to publish the first iteration of the node-red-contrib-twc-weather then circle back to enhancements.

1 Like

I included this enhancement in the recently released node-red-contrib-twc-weather nodes. The node will accept yyyymmdd, yyyy/mm/dd, yyyy-mm-dd or a timestamp. That allows you to use the Node-RED Dashboard date picker to select a date in the past and get the weather history.

2 Likes

The node-red-contrib-sun-position node has a time compare and change node which is designed for time formatting.

or