Table of Contents

    Input Validation

    Programming Mastery

    Input Validation

    Learn how to check user input before using it so that applications can prevent invalid data, reduce bugs, and protect against common security risks.

    Introduction

    Input validation is one of the most important secure programming practices.

    Every application receives input from users, forms, URLs, files, APIs, databases, cookies, headers, and external systems. If this input is not checked properly, the application may behave incorrectly, crash, store bad data, or become vulnerable to attacks.

    Input validation means checking whether input is correct, safe, and expected before the program uses it.

    A secure program never blindly trusts input. It checks whether the input has the correct type, length, format, range, and business meaning before processing it.

    Easy Real-Life Example

    Input Validation as Security Checking at a Gate

    Imagine a school gate. The security guard does not allow everyone to enter without checking. The guard checks ID card, purpose, timing, and permission.

    School Gate:
    Check ID card
    Check visitor purpose
    Check allowed entry time
    Reject unknown visitors
    
    Software Application:
    Check input type
    Check input length
    Check input range
    Check input format
    Reject invalid input

    Input validation works like a gatekeeper for your application. It allows expected data and rejects unsafe or incorrect data.

    What is Input Validation?

    Input validation is the process of checking data before accepting, storing, processing, or displaying it.

    It ensures that only properly formed and expected data enters the application workflow.

    Key Idea: Validate input before using it, not after damage is already done.

    Simple Example

    Requirement:
    Marks must be between 0 and 100.
    
    Input:
    marks = 150
    
    Validation:
    150 is greater than 100.
    
    Result:
    Reject input and show "Invalid marks".

    Without validation, the application may calculate wrong results using invalid data.

    Why Input Validation is Important

    Input validation is important because applications often receive unexpected data. Users may make mistakes, attackers may send harmful input, and external systems may send malformed data.

    Benefits of Input Validation

    • Prevents invalid data from entering the system.
    • Reduces application crashes.
    • Helps prevent injection-related risks.
    • Improves data quality.
    • Protects business rules.
    • Improves user experience with clear error messages.
    • Makes debugging easier.
    • Reduces downstream processing errors.
    • Improves application reliability.
    • Supports secure programming habits.

    What Can Go Wrong Without Input Validation?

    If input is not validated, the application may accept data that it cannot safely process.

    Without Input Validation

    • Users can enter empty required values.
    • Numbers may be entered where text is expected.
    • Text may be entered where numbers are expected.
    • Negative quantities may be accepted.
    • Large input may cause performance problems.
    • Invalid email or phone format may be stored.
    • Unsafe characters may enter sensitive processing.
    • Business rules may be bypassed.

    With Input Validation

    • Only expected data is accepted.
    • Invalid data is rejected early.
    • Application behavior becomes predictable.
    • Security risks are reduced.
    • Data becomes cleaner and more reliable.
    • Error messages become clearer.
    • Testing becomes easier.
    • Business rules are enforced properly.

    Sources of Input

    Input does not only come from forms. Secure programmers must validate data from many sources.

    Input Source Example Validation Need
    User Form Name, email, password, marks Check required fields, length, format, and range.
    URL Parameter studentId=101 Check type, range, and authorization.
    API Request JSON body from another application Validate schema, required fields, and data types.
    Uploaded File Image, PDF, document Check file type, size, name, and content rules.
    Cookie Session or preference value Do not blindly trust client-controlled values.
    External System Data from partner system or database Validate before processing, even if source seems internal.

    Basic Validation Checks

    Input validation usually checks multiple conditions.

    Validation Check Question Example
    Required Check Is the input present? Email should not be empty.
    Type Check Is the input the correct data type? Age must be a number.
    Length Check Is the input within allowed length? Username must be 3 to 20 characters.
    Range Check Is the value within allowed minimum and maximum? Marks must be 0 to 100.
    Format Check Does input follow expected pattern? Email must follow email format.
    Allowed Values Check Is input one of the accepted options? Role must be Student, Teacher, or Admin.
    Business Rule Check Does input make sense in the business context? Start date should not be after end date.

    Syntactic Validation

    Syntactic validation checks whether input has the correct structure or format.

    Examples:
    - Email should contain valid email structure.
    - Date should follow expected date format.
    - Phone number should contain expected digits.
    - Product code should follow required pattern.
    - Postal code should match allowed format.

    Syntactic validation answers the question: Is the input written in the correct form?

    Semantic Validation

    Semantic validation checks whether the value makes sense in the business context.

    Examples:
    - Start date must be before end date.
    - Withdrawal amount must not exceed account balance.
    - Product quantity must be available in stock.
    - Student marks must be between 0 and 100.
    - Discount percentage must not be more than 100.

    Semantic validation answers the question: Does the input make sense for this situation?

    Syntactic vs Semantic Validation

    Validation Type Meaning Example
    Syntactic Validation Checks format or structure. Date must be in correct format.
    Semantic Validation Checks meaning or business correctness. Start date must be before end date.

    Allowlist Validation

    Allowlist validation means accepting only known safe and expected values.

    This is usually safer than trying to block known bad values because attackers may find new ways to bypass blocklists.

    Weak Blocklist Thinking

    Reject only values that look dangerous.
    
    Problem:
    Attackers may use a new pattern that is not blocked.

    Better Allowlist Thinking

    Accept only values that are expected.
    
    allowedRoles = ["Student", "Teacher", "Admin"]
    
    IF role is in allowedRoles THEN
        ACCEPT role
    ELSE
        REJECT role
    END IF
    Secure Habit: Prefer allowlist validation wherever possible.

    Reject Invalid Input

    When input fails validation, the application should reject it safely and clearly.

    Do not continue processing invalid input.

    INPUT quantity
    
    IF quantity is not a number THEN
        DISPLAY "Invalid quantity"
        STOP
    END IF
    
    IF quantity <= 0 THEN
        DISPLAY "Quantity must be greater than zero"
        STOP
    END IF
    
    PROCESS quantity

    Stopping early prevents invalid data from reaching later parts of the program.

    Validate on the Server Side

    Client-side validation improves user experience, but it should not be treated as the main security control.

    Users or attackers can bypass browser checks and send requests directly to the server.

    Unsafe Assumption

    • The form already validates input.
    • The browser prevents wrong values.
    • The user cannot bypass the interface.

    Secure Practice

    • Validate on the client for user experience.
    • Validate on the server for security.
    • Validate again at important trust boundaries.

    Multi-Level Validation

    Multi-level validation means validating data at more than one layer when needed.

    Validation Layers:
    1. User interface layer
    2. API layer
    3. Application/business logic layer
    4. Database constraints
    5. File processing layer

    Each layer may validate different things depending on the context.

    Length Validation

    Length validation checks whether input is too short or too long.

    This protects the application from empty values, oversized values, storage problems, and some denial-of-service style risks.

    FUNCTION validateUsername(username)
        IF username is empty THEN
            RETURN "Username is required"
        END IF
    
        IF length of username < 3 THEN
            RETURN "Username is too short"
        END IF
    
        IF length of username > 20 THEN
            RETURN "Username is too long"
        END IF
    
        RETURN "Valid username"
    END FUNCTION

    Range Validation

    Range validation checks whether numeric values are within allowed limits.

    FUNCTION validateMarks(marks)
        IF marks is not a number THEN
            RETURN "Invalid marks"
        END IF
    
        IF marks < 0 OR marks > 100 THEN
            RETURN "Marks must be between 0 and 100"
        END IF
    
        RETURN "Valid marks"
    END FUNCTION

    Range validation is useful for marks, age, quantity, price, percentage, date limits, and rating values.

    Format Validation

    Format validation checks whether input follows an expected pattern.

    Examples:
    - Email format
    - Phone number format
    - Date format
    - Student roll number format
    - Product code format
    - Postal code format

    Example: Roll Number Format

    Requirement:
    Roll number should start with "STU-" followed by four digits.
    
    Valid:
    STU-1001
    
    Invalid:
    1001
    STUDENT-1001
    STU-ABCD

    File Upload Validation

    File upload validation is important because uploaded files can be misused if the application accepts anything without checking.

    File Validation Checks

    • Check whether file upload is required or optional.
    • Allow only required file types.
    • Check file size limit.
    • Validate file name length.
    • Do not blindly trust the original file name.
    • Store uploaded files safely.
    • Scan uploaded files when required by policy or system design.
    • Do not execute uploaded files as program code.

    Sanitization vs Validation

    Validation and sanitization are related, but they are not the same.

    Validation Sanitization
    Checks whether input is acceptable. Cleans or transforms input to make it safer for a purpose.
    Invalid input is usually rejected. Input may be modified before use.
    Example: Marks must be 0 to 100. Example: Remove unnecessary spaces from username.
    Important: Do not rely only on sanitization. First decide what valid input means.

    Validation and Output Encoding

    Input validation checks whether data is acceptable before processing. Output encoding prepares data safely for a specific output context.

    Valid input may still need output encoding when shown in HTML, placed in a URL, written in JSON, or used in another context.

    Input validation asks:
    "Does this value belong here?"
    
    Output encoding asks:
    "How should this value be safely displayed or sent?"

    Both are useful, but they solve different problems.

    Input Validation and Databases

    When input is used with databases, validation is important, but validation alone should not be the only defense.

    Secure programs should treat user input as data and use safe database handling methods rather than directly combining raw input into database commands.

    Unsafe idea:
    Directly join user input into database command text.
    
    Safer idea:
    Validate input and use parameterized query or safe database method.

    Student-Friendly Example: Marks Validation

    Bad Code

    INPUT marks
    
    IF marks >= 40 THEN
        DISPLAY "Pass"
    ELSE
        DISPLAY "Fail"
    END IF

    This code does not check whether marks is a number or whether marks is between 0 and 100.

    Improved Secure Version

    INPUT marks
    
    IF marks is not a number THEN
        DISPLAY "Invalid marks"
        STOP
    END IF
    
    IF marks < 0 OR marks > 100 THEN
        DISPLAY "Marks must be between 0 and 100"
        STOP
    END IF
    
    IF marks >= 40 THEN
        DISPLAY "Pass"
    ELSE
        DISPLAY "Fail"
    END IF

    The improved version validates input before using it.

    Real-World Example: E-Commerce Quantity Validation

    Bad Code

    INPUT quantity
    INPUT price
    
    totalAmount = quantity * price
    
    DISPLAY totalAmount

    This code does not check whether quantity and price are valid.

    Improved Secure Version

    INPUT quantity
    INPUT price
    
    IF quantity is not a number OR quantity <= 0 THEN
        DISPLAY "Invalid quantity"
        STOP
    END IF
    
    IF price is not a number OR price <= 0 THEN
        DISPLAY "Invalid price"
        STOP
    END IF
    
    IF quantity > 100 THEN
        DISPLAY "Quantity limit exceeded"
        STOP
    END IF
    
    totalAmount = quantity * price
    
    DISPLAY totalAmount

    The improved version validates type, range, and business limit before calculation.

    Example: Role Validation

    Role values should usually be selected from allowed values rather than accepted freely.

    allowedRoles = ["Student", "Teacher", "Admin"]
    
    INPUT selectedRole
    
    IF selectedRole is not in allowedRoles THEN
        DISPLAY "Invalid role"
        STOP
    END IF
    
    SAVE selectedRole

    This prevents unexpected role names from entering the system.

    Common Input Validation Mistakes

    Mistakes

    • Trusting input because it came from a form.
    • Validating only on the client side.
    • Not checking empty values.
    • Not checking data type.
    • Not checking length limits.
    • Not checking numeric range.
    • Using blocklists as the only defense.
    • Accepting any uploaded file type.
    • Assuming internal data is always safe.
    • Continuing to process input after validation fails.

    Better Habits

    • Validate every untrusted input.
    • Validate on the server side.
    • Use allowlists where possible.
    • Check required fields.
    • Check type, length, range, and format.
    • Reject invalid input early.
    • Use structured validation for JSON or XML.
    • Validate files before upload processing.
    • Validate at trust boundaries.
    • Use clear and safe error messages.

    Best Practices for Input Validation

    Recommended Practices

    • Validate input as early as possible.
    • Validate all data from untrusted sources.
    • Use server-side validation for security.
    • Use client-side validation only for user experience support.
    • Prefer allowlist validation over blocklist validation.
    • Check data type, length, range, and format.
    • Apply both syntactic and semantic validation.
    • Reject invalid input safely.
    • Use safe error messages.
    • Validate file uploads carefully.
    • Validate structured data using schemas when applicable.
    • Use centralized validation functions where practical.
    • Test validation with normal, invalid, boundary, and unexpected inputs.

    Prerequisites Before Learning Input Validation

    Students should understand the following topics before learning input validation deeply:

    Required Knowledge

    • Basic programming syntax.
    • Variables and data types.
    • Conditional statements.
    • Functions or methods.
    • Input and output handling.
    • Testing basics.
    • Secure programming practices.
    • Basic web form and API concepts.

    Trace Table Example: Validate Marks

    FUNCTION validateMarks(marks)
        IF marks is not a number THEN
            RETURN "Invalid marks"
        END IF
    
        IF marks < 0 OR marks > 100 THEN
            RETURN "Marks must be between 0 and 100"
        END IF
    
        RETURN "Valid marks"
    END FUNCTION
    Test Case Input Expected Result Reason
    TC_001 80 Valid marks Number within valid range.
    TC_002 0 Valid marks Lowest valid boundary.
    TC_003 100 Valid marks Highest valid boundary.
    TC_004 -1 Marks must be between 0 and 100 Below valid range.
    TC_005 101 Marks must be between 0 and 100 Above valid range.
    TC_006 ABC Invalid marks Input is not numeric.

    Practice Activity: Add Input Validation

    Improve the following pseudocode by adding input validation.

    INPUT age
    
    IF age >= 18 THEN
        DISPLAY "Eligible"
    ELSE
        DISPLAY "Not eligible"
    END IF

    Sample Improved Version

    INPUT age
    
    IF age is not a number THEN
        DISPLAY "Invalid age"
        STOP
    END IF
    
    IF age < 0 OR age > 120 THEN
        DISPLAY "Age must be between 0 and 120"
        STOP
    END IF
    
    IF age >= 18 THEN
        DISPLAY "Eligible"
    ELSE
        DISPLAY "Not eligible"
    END IF

    Practice Test Cases

    Test Case Input Age Expected Output
    TC_001 20 Eligible
    TC_002 18 Eligible
    TC_003 17 Not eligible
    TC_004 -5 Age must be between 0 and 120
    TC_005 150 Age must be between 0 and 120
    TC_006 Text value Invalid age

    Mini Quiz

    1

    What is input validation?

    Input validation is the process of checking whether input data is correct, expected, and safe before using it.

    2

    Why should input be validated?

    Input should be validated to prevent invalid data, reduce crashes, protect business rules, and reduce security risks.

    3

    What is allowlist validation?

    Allowlist validation accepts only known safe and expected values and rejects everything else.

    4

    What is the difference between syntactic and semantic validation?

    Syntactic validation checks format, while semantic validation checks whether the value makes sense in the business context.

    5

    Is client-side validation enough for security?

    No. Client-side validation helps user experience, but server-side validation is required for security.

    Interview Questions on Input Validation

    1

    Define input validation.

    Input validation is the process of checking input against expected rules before accepting or processing it.

    2

    What are common input validation checks?

    Common checks include required fields, type checks, length checks, range checks, format checks, allowed values, and business rule checks.

    3

    Why is allowlist validation preferred?

    Allowlist validation is preferred because it accepts only expected values instead of trying to block every possible bad value.

    4

    Why should validation happen early?

    Validation should happen early so invalid or unsafe data does not reach later parts of the application workflow.

    5

    What is one mistake beginners make with input validation?

    A common mistake is validating only in the browser and not validating again on the server side.

    Quick Summary

    Concept Meaning
    Input Validation Checking input before using it.
    Required Check Ensures input is not missing.
    Type Check Ensures input is the expected data type.
    Length Check Ensures input is not too short or too long.
    Range Check Ensures numeric or date values are within valid limits.
    Format Check Ensures input follows expected pattern.
    Allowlist Accepts only known safe values.
    Server-Side Validation Security validation performed on trusted backend logic.

    Final Takeaway

    Input validation is a core secure programming practice. It protects applications by checking data before it is processed, stored, or displayed. Students should remember to validate all untrusted input, check type, length, range, format, and allowed values, prefer allowlist validation, reject invalid input early, validate on the server side, and test normal, invalid, boundary, and unexpected cases. Good input validation improves security, reliability, data quality, and user experience.