Validation Function

The validation function can be defined for a command parameter to provide validation for input, thereby automating validation before the command is even invoked. The name of the validation function must match the name of an actual function in the command class.

The validation function is invoked before after the user enters the command and before the invoke function is invoked. All parameter values and switches available on the command line will be present when the function is invoked.


The following class defines a validation function for ParameterOne.

    class TestCommand : InputCommand
        public string ParameterOne { get; set; }

        public void ValidateParameterOneValue(ValidationFunctionContext context)
              if(context.Value.Length > 20)
                   context.IsValid = false;
                   context.Message = "The value entered for ParameterOne is too long";

        public override void Invoke(CommandInvocationContext context)
            // do something


The ValidationFunctionContext contains the information needed to validate the parameter value.

    public class ValidationFunctionContext
        public string Value { get; set; }

        public bool IsValid { get; set; }
        public string Message { get; set; }
        internal ValidationFunctionContext(string value)
            this.Value = value;

            this.IsValid = true;

The validation function should use the Value property on the context when evaluating the parameter value as this is always guaranteed to be the most up to date value. If validation fails for the value of the parameter, set the IsValid property to false. Otherwise, it is true by default. The Message property can optionally be set to print a custom validation message to the console window. If no message is provided, a default validation message will be displayed.

see also Parameter Attribute

Last edited Jun 15, 2013 at 8:13 PM by jeffhewitt, version 4


No comments yet.