Get property name in custom validator

Hi folks,

When developing a node, you can apply your own custom validators to validate the node properties.

RED.nodes.registerType('myType',{
      defaults: {
           myProperty: {value:'', validate:function(v) {
                debugger; 
           }}
      ...

But now I have a case where there are a lot of similar properties. So I would like to add the same validator function to all those properties:

RED.nodes.registerType('myType',{
      defaults: {
           myProperty1: {value:'', validate:myValidationFunction(v)},
           myProperty2: {value:'', validate:myValidationFunction(v)},
           myProperty3: {value:'', validate:myValidationFunction(v)},
           myProperty4: {value:'', validate:myValidationFunction(v)},
      ...

But then I need to have the property name ("myProperty1", "myProperty2" ...) available inside that validation function. But I don't think it is available...
When I go up one step in the call stack it is still available, but I don't think it is passed to the validate function:

image

Does anybody know a way to get the property name?

Thanks !
Bart

You've already dug into the code to see it isn't passed in... not much to add on that.

The other approach is to pass it in yourself ...

myProperty1: {value:'', validate:function(v) { return myValidationFunction.call(this,"myProperty1",v) }},
myProperty2: {value:'', validate:function(v) { return myValidationFunction.call(this,"myProperty2",v) }},

Hey Nick,

Thanks for the workaround! Will use that.

You never know :wink:

I did a small update of the red.js file to pass the 'property' name as an extra parameter to the validation function:

if (valid && "validate" in definition[property]) {
   try {
       valid = definition[property].validate.call(node,value, property);
   } catch(err) {
       console.log("Validation error:",node.type,node.id,"property: "+property,"value:",value,err);
   }
}

And then indeed I have the property name available in a validation function with two parameters:
image

And my old validation function with one parameter still works fine (i.e. it still gets the property value):
image

=> Existing validators wouldn't be broken, when you should consider to add this change to Node-RED.

And when I remove my change again, my new validator just gets called with an undefined property value:
image

=> To avoid that the validators (with two parameters) run into problems on older Node-RED versions (which don't pass the property name), perhaps the documentation could mention that "you should always check whether property is undefined!".

Or have I forgotten something?
It would help me a lot if you would consider to pass the property name to validators in the future ...

Thanks!
Bart