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
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);
}
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);
}
}
}
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.