w3resource

Rust user input validation: Propagate Validation Errors

Rust Error Propagation: Exercise-5 with Solution

Write a Rust program that processes user input, validates it against certain rules, and propagates validation errors.

Sample Solution:

Rust Code:

use std::io;
use std::error::Error;

// Function to validate user input against certain rules
fn validate_input(input: &str) -> Result<(), Box<dyn Error>> {
    // Check if the input length is within a valid range
    if input.len() < 3 || input.len() > 10 {
        return Err("Input length must be between 3 and 10 characters.".into());
    }
    
    // Check if the input contains only alphanumeric characters
    if !input.chars().all(|c| c.is_ascii_alphanumeric()) {
        return Err("Input must contain only alphanumeric characters.".into());
    }
    
    Ok(()) // Return Ok if input passes all validation rules
}

fn main() -> Result<(), Box<dyn Error>> {
    println!("Enter your username (3 to 10 alphanumeric characters):");
    
    let mut input = String::new();
    io::stdin().read_line(&mut input)?;
    
    let input = input.trim(); // Trim leading and trailing whitespace
    
    // Validate user input
    match validate_input(input) {
        Ok(_) => println!("Input is valid!"),
        Err(err) => eprintln!("Validation error: {}", err),
    }
    
    Ok(()) // Return Ok if the program completes successfully
}

Output:

Enter your username (3 to 10 alphanumeric characters): abc123
Input is valid!
 
Enter your username (3 to 10 alphanumeric characters): Ab@#12n
Validation error: Input must contain only alphanumeric characters.

Explanation:

Here is a brief explanation of the above Rust code:

  • Imports:
    • use std::io: Imports the Input/Output module from the standard library, allowing interaction with the standard input stream (stdin) for user input.
    • use std::error::Error: Imports the "Error" trait from the standard library, which is used for error handling.
  • validate_input Function:
    • This function takes a string slice (&str) representing the user input and returns a Result<(), Box<dyn Error>>.
    • It checks if the input length is within the range of 3 to 10 characters. If not, it returns an error indicating that the input length must be between 3 and 10 characters.
    • It verifies if the input contains only alphanumeric characters using the "chars()" iterator and the "is_ascii_alphanumeric()" method. If any character fails this check, it returns an error indicating that the input must contain only alphanumeric characters.
    • If the input passes all validation rules, it returns Ok(()), indicating that the input is valid.
  • main Function:
    • This is the entry point of the program and returns a Result<(), Box<dyn Error>>.
    • It prompts the user to enter a username within the specified range and format.
    • It reads the user input from the standard input (stdin) and stores it in a mutable 'String' variable.
    • Leading and trailing whitespace is trimmed from the input using the "trim()" method.
    • The "validate_input()" function validates user input.
    • If the input is valid (Ok(_)), it prints a message indicating that the input is valid. If there's a validation error (Err(err)), it prints an error message indicating the validation error.
    • Finally, it returns Ok(()) if the program completes successfully

Rust Code Editor:

Previous: Rust Configuration Parser: Apply Settings & Handle errors.
Next: Rust user input validation: Efficient error propagation.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/rust/error_handling/rust-error-propagation-exercise-5.php