cancel
Showing results for 
Search instead for 
Did you mean: 

adding error messages to validate fields

kavindu21
Deputy Chef I
Deputy Chef I

how to add validations for the fields here and display errors when the fields are empty?

connection: {

  fields: [
    {
      name: "username",
      hint: "Your email used for login"
    },
    {
      name: "password",
      optional: false,
      control_type: "password",
    }
  ],

  authorization: {
    type: "basic_auth",

    credentials: lambda do |connection|
      user(connection["username"])
      password(connection["password"])
    end
  }
}
1 REPLY 1

shivakumara
Executive Chef I
Executive Chef I

Hi @kavindu21 ,

Please check this sample code provided here, please let me know if this helps. 

Thanks and regards,
Shivakumar K A

{
  title: 'Sample Action with Validation',
  
  input_fields: ->() {
    [
      {
        name: 'first_name',
        label: 'First Name',
        type: 'string',
        required: true, # This ensures the field is mandatory
        control_type: 'text'
      },
      {
        name: 'last_name',
        label: 'Last Name',
        type: 'string',
        required: true, # This ensures the field is mandatory
        control_type: 'text'
      },
      {
        name: 'email',
        label: 'Email',
        type: 'string',
        required: true, # This ensures the field is mandatory
        control_type: 'email'
      }
    ]
  },
  
  execute: ->(input) {
    # Sample logic when the fields are valid and populated
    {
      message: "Validation passed! First name: #{input['first_name']}, Last name: #{input['last_name']}, Email: #{input['email']}"
    }
  },
  
  # Custom field validation (can be optional, for additional checks)
  validate_input: ->(input) {
    errors = []
    
    if input['first_name'].blank?
      errors << "First name cannot be blank."
    end
    
    if input['last_name'].blank?
      errors << "Last name cannot be blank."
    end
    
    if input['email'].blank?
      errors << "Email cannot be blank."
    elsif !(input['email'] =~ URI::MailTo::EMAIL_REGEXP)
      errors << "Email format is invalid."
    end

    # Raise validation error if there are errors
    raise(errors.join(', ')) unless errors.empty?
  }
}