Simple Number Validator
Part of the Logic & Flow section of Coddy's GO journey — lesson 67 of 68.
Challenge
EasyCreate a number validation system that demonstrates how interfaces define behavior contracts while custom errors provide meaningful feedback when validation fails. This challenge will test your ability to create interfaces, implement them with custom types, and handle validation errors appropriately.
You will receive two inputs:
- A string containing numbers to validate separated by commas (e.g.,
"45,150,25,200,75") - A string containing the validation range in the format
"min:max"(e.g.,"1:100")
Your task is to:
- Define a
Validatorinterface with a single method:Validate() error - Create a custom error type called
ValidationErrorstruct with two fields:Value(int) andMessage(string) - Implement the
Error() stringmethod forValidationErrorthat returns the message in the format:"Validation failed: [message] (value: [value])" - Create a
NumberValidatorstruct with three fields:Number(int),Min(int), andMax(int) - Implement the
Validate() errormethod forNumberValidatorthat:- Returns
nilif the number is within the valid range (inclusive) - Returns a
ValidationErrorwith message"number below minimum range"if the number is less than the minimum - Returns a
ValidationErrorwith message"number above maximum range"if the number is greater than the maximum
- Returns
- Parse the first input by splitting on commas to get individual number strings
- Parse the second input by splitting on colons to extract minimum and maximum values
- Convert all string values to integers using the
strconvpackage - Display the validation header:
"=== NUMBER VALIDATION SYSTEM ===" - Display the validation parameters:
"Validating numbers in range [min] to [max]" - For each number:
- Create a
NumberValidatorinstance with the number and range values - Call the
Validate()method on the validator - If validation passes (error is
nil), display:"✓ [number] is valid" - If validation fails (error is not
nil), display:"✗ [error_message]"
- Create a
- Display validation summary:
"=== VALIDATION SUMMARY ===""Total numbers checked: [total_count]""Valid numbers: [valid_count]""Invalid numbers: [invalid_count]"
- Display the completion message:
"Number validation completed successfully"
Use the strings package to split input strings, the strconv package to convert strings to integers, and the fmt package for formatted output. This challenge demonstrates how to create flexible validation systems using interfaces while providing detailed error information through custom error types.
Try it yourself
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
// Read input
var numbersInput string
var rangeInput string
fmt.Scanln(&numbersInput)
fmt.Scanln(&rangeInput)
// Parse the inputs
numberStrings := strings.Split(numbersInput, ",")
rangeParts := strings.Split(rangeInput, ":")
// Convert range values to integers
min, _ := strconv.Atoi(rangeParts[0])
max, _ := strconv.Atoi(rangeParts[1])
// TODO: Write your code below
// 1. Define the Validator interface
// 2. Create the ValidationError struct and implement Error() method
// 3. Create the NumberValidator struct and implement Validate() method
// 4. Process each number and validate it
// 5. Display the results and summary
// Display validation header
fmt.Println("=== NUMBER VALIDATION SYSTEM ===")
fmt.Printf("Validating numbers in range %d to %d\n", min, max)
// Process each number here
// Display validation summary
fmt.Println("=== VALIDATION SUMMARY ===")
// Add summary output here
fmt.Println("Number validation completed successfully")
}All lessons in Logic & Flow
1Advanced Control Flow
Switch with `fallthrough`Breaking from Nested LoopsContinuing a Specific LoopThe `goto` StatementRecap - Advanced Loop Control4Project: Simple Task List
Project SetupAdding a Task2Structs and Methods
Defining Methods on StructsValue ReceiversPointer ReceiversChoosing ReceiversMethods vs FunctionsRecap - Struct Behavior5Maps In-Depth
Maps of StructsPointers as Map ValuesTesting for Nil MapsComparing MapsRecap - Word Frequency Counter3Interfaces (The Basics)
What is an Interface?Defining an InterfaceImplementing an InterfaceUsing Interface TypesEmpty InterfaceType AssertionsType SwitchRecap - Shapes and Behaviors