Go Program to Validate User Input with Error Handling

Introduction

Validating user input is a critical part of any application to ensure that the input meets expected criteria before processing. In Go, you can validate input and handle errors effectively using conditional statements and the error type. This guide will demonstrate how to write a Go program that validates user input and handles errors gracefully.

Problem Statement

Create a Go program that:

  • Prompts the user for input.
  • Validates the input based on specific criteria (e.g., ensuring it’s a positive integer).
  • Handles invalid input by displaying appropriate error messages.
  • Continues to prompt the user until valid input is provided.

Example:

  • Validation: The user must enter a positive integer.
  • Output:
    Enter a positive integer: -5
    Error: input must be a positive integer
    Enter a positive integer: 10
    You entered: 10
    

Solution Steps

  1. Import the Necessary Packages: Use import "fmt" and import "strconv" for input handling and conversions.
  2. Write a Function to Validate the Input: Implement a function that checks whether the input meets the required criteria and returns an error if it doesn’t.
  3. Handle Input Validation in the Main Function: Use a loop to repeatedly prompt the user until valid input is provided.
  4. Display the Result: Use fmt.Println to display the result or error messages.

Go Program

package main

import (
    "errors"
    "fmt"
    "strconv"
)

// Step 2: Implement a function to validate the input
func validatePositiveInteger(input string) (int, error) {
    number, err := strconv.Atoi(input)
    if err != nil {
        return 0, errors.New("input must be a valid integer")
    }
    if number <= 0 {
        return 0, errors.New("input must be a positive integer")
    }
    return number, nil
}

/**
 * Go Program to Validate User Input with Error Handling
 * Author: https://www.javaguides.net/
 */
func main() {
    var input string
    var number int
    var err error

    // Step 3: Handle input validation in the main function
    for {
        fmt.Print("Enter a positive integer: ")
        fmt.Scanln(&input)

        number, err = validatePositiveInteger(input)
        if err != nil {
            fmt.Println("Error:", err)
        } else {
            break
        }
    }

    // Step 4: Display the result
    fmt.Println("You entered:", number)
}

Explanation

Step 2: Implement a Function to Validate the Input

  • The validatePositiveInteger function performs the following tasks:
    • It converts the input string to an integer using strconv.Atoi.
    • If the input is not a valid integer, the function returns an error with the message "input must be a valid integer."
    • If the integer is zero or negative, the function returns an error with the message "input must be a positive integer."
    • If the input is a positive integer, the function returns the integer and nil for the error.

Step 3: Handle Input Validation in the Main Function

  • The main function prompts the user for input in a loop.
    • It repeatedly calls validatePositiveInteger to check if the input is valid.
    • If the input is invalid, the error message is displayed, and the user is prompted again.
    • The loop continues until valid input is provided.

Step 4: Display the Result

  • Once valid input is provided, the program prints the positive integer entered by the user.

Output Example

Example 1:

Enter a positive integer: -5
Error: input must be a positive integer
Enter a positive integer: 0
Error: input must be a positive integer
Enter a positive integer: 10
You entered: 10

Example 2:

Enter a positive integer: abc
Error: input must be a valid integer
Enter a positive integer: 5
You entered: 5

Example 3:

Enter a positive integer: 20
You entered: 20

Example Explanation:

  • In the first example, the user initially enters invalid input (-5 and 0), and the program correctly identifies and handles the errors, prompting the user again until valid input (10) is provided.
  • In the second example, the user enters a non-integer string ("abc"), and the program handles the error before accepting a valid integer (5).
  • In the third example, the user enters valid input (20) on the first attempt, and the program proceeds without any errors.

Conclusion

This Go program demonstrates how to validate user input with error handling. It covers key concepts such as converting strings to integers, validating the input, handling errors, and using loops to ensure that the user provides valid input. This example is useful for beginners learning Go programming and understanding how to manage user input and errors effectively.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top