C Input Validation

Ensuring user input is safe and correct

โœ… What is Input Validation?

Input validation ensures user data meets expected criteria before processing. It prevents crashes, security vulnerabilities, and unexpected behavior by checking data format, range, and type correctness.


#include <stdio.h>

int main() {
    int age;
    printf("Enter your age: ");
    
    if (scanf("%d", &age) == 1 && age >= 0 && age <= 150) {
        printf("Valid age: %d\n", age);
    } else {
        printf("Invalid age entered!\n");
    }
    return 0;
}
                                    

Output (with input 25):

Enter your age: 25

Valid age: 25

Key Input Validation Concepts

๐Ÿ”ข

Type Checking

Verify input matches expected data type

if (scanf("%d", #) != 1) {
    // Invalid integer
}
๐Ÿ“

Range Validation

Check if values are within acceptable limits

if (age < 0 || age > 150) {
    // Invalid range
}
๐Ÿ“

String Validation

Validate string length and content

if (strlen(name) == 0) {
    // Empty string
}
๐Ÿงน

Input Sanitization

Clean and format input data

// Clear input buffer
while (getchar() != '\n');

๐Ÿ”น Validating Integer Input

Robust integer input validation with comprehensive error handling ensures programs handle invalid data gracefully. Check if scanf() successfully read an integer, verify the value falls within acceptable ranges, and clear the input buffer if reading fails. This prevents program crashes and unexpected behavior from invalid user input. Implement validation loops that repeat until the user enters valid data, provide clear error messages explaining requirements, and educate users about acceptable input formats to reduce validation failures.

#include <stdio.h>

int getValidInteger(int min, int max) {
    int num;
    char buffer[100];
    
    while (1) {
        printf("Enter a number (%d-%d): ", min, max);
        
        if (fgets(buffer, sizeof(buffer), stdin) != NULL) {
            if (sscanf(buffer, "%d", #) == 1) {
                if (num >= min && num <= max) {
                    return num;
                }
                printf("Number must be between %d and %d\n", min, max);
            } else {
                printf("Invalid input. Please enter a number.\n");
            }
        }
    }
}

int main() {
    int score = getValidInteger(0, 100);
    printf("Valid score entered: %d\n", score);
    return 0;
}

Output (with input 85):

Enter a number (0-100): 85

Valid score entered: 85

๐Ÿ”น String Input Validation

String input validation requires checking both string length and content to prevent buffer overflows and security issues. Use fgets() instead of gets() to safely read strings with specified length limits. Verify strings contain only expected characters, are within maximum length constraints, and don't exceed allocated buffer sizes. Implement proper error handling for incomplete string reads and provide clear user guidance about string requirements, character limits, and acceptable formats to ensure data integrity.

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int isValidName(char *name) {
    int len = strlen(name);
    
    // Check length
    if (len < 2 || len > 50) {
        return 0;
    }
    
    // Check if all characters are alphabetic or space
    for (int i = 0; i < len; i++) {
        if (!isalpha(name[i]) && name[i] != ' ') {
            return 0;
        }
    }
    
    return 1;
}

int main() {
    char name[100];
    
    printf("Enter your name: ");
    fgets(name, sizeof(name), stdin);
    
    // Remove newline if present
    name[strcspn(name, "\n")] = 0;
    
    if (isValidName(name)) {
        printf("Hello, %s!\n", name);
    } else {
        printf("Invalid name format!\n");
    }
    
    return 0;
}

Output (with input "John Doe"):

Enter your name: John Doe

Hello, John Doe!

๐Ÿ”น Email Format Validation

Basic email format validation checks for required components like the @ symbol and domain structure. A simple validation approach looks for the presence of an @ character and ensures text exists before and after it. While a basic check doesn't verify email delivery capability, it prevents obviously invalid formats from entering your system. Use character checking functions to validate each part of the email address, reject addresses with invalid characters, and provide feedback about what makes an email format invalid to help users correct their input.

#include <stdio.h>
#include <string.h>

int isValidEmail(char *email) {
    int len = strlen(email);
    int atCount = 0, dotAfterAt = 0;
    
    // Basic checks
    if (len < 5 || email[0] == '@' || email[len-1] == '@') {
        return 0;
    }
    
    // Count @ symbols and check for dot after @
    for (int i = 0; i < len; i++) {
        if (email[i] == '@') {
            atCount++;
            // Look for dot after @
            for (int j = i + 1; j < len; j++) {
                if (email[j] == '.') {
                    dotAfterAt = 1;
                    break;
                }
            }
        }
    }
    
    return (atCount == 1 && dotAfterAt);
}

int main() {
    char email[100];
    
    printf("Enter email: ");
    scanf("%99s", email);
    
    if (isValidEmail(email)) {
        printf("Valid email format: %s\n", email);
    } else {
        printf("Invalid email format!\n");
    }
    
    return 0;
}

Output (with input "[email protected]"):

Enter email: [email protected]

Valid email format: [email protected]

๐Ÿง  Test Your Knowledge

What does scanf() return when it successfully reads input?