Input Validation

Input Validation ensures that every character entered into the control adheres to the specified format, maintaining data integrity and preventing unwanted input.

Overview

This feature leverages regular expression-based validation to scrutinize each input character in real time. Developers can specify a custom validation pattern, and when StrictValidation is enabled, any input that does not match the criteria is automatically rejected and cleared, with detailed events raised for further handling.


Key Points

Key Point
Description

Custom Regex Patterns

Developers can set a custom regex pattern via the ValidationPattern property to restrict the allowed characters for each digit in the control.

Strict Validation

When StrictValidation is enabled, any input that does not meet the validation criteria is immediately cleared, ensuring the control only contains valid data.

Automatic Error Events

The control raises a ValidationFailed event when invalid characters are detected, providing detailed information about which indices and characters failed.

Mask Conversion

A private mechanism converts an input mask into a regex pattern, ensuring that standard mask characters are appropriately translated into validation rules.


Best Practices

Best Practice
Recommendation

Define Clear Validation Patterns

Use the ValidationPattern property to specify exactly what characters are allowed (e.g., digits only, alphanumeric, etc.) to ensure only valid data is entered.

Enable Strict Validation

Keep StrictValidation enabled in security-sensitive scenarios to automatically remove any non-conforming characters, preserving data integrity.

Monitor Validation Events

Subscribe to the ValidationFailed event to log or notify users when an invalid character is rejected, enabling real-time troubleshooting and user guidance.

Leverage Input Masks Where Appropriate

Although the InputMask property is private, understand that its underlying mechanism helps construct the validation regex; designing your validation pattern with similar rules in mind can be beneficial.


Common Pitfalls

Pitfall
Explanation
Mitigation

Overly Permissive Patterns

A loosely defined validation pattern may allow unintended characters, compromising the integrity of the entered code.

Test your regex thoroughly to ensure it restricts input to the desired character set.

Overly Restrictive Patterns

An excessively strict validation rule may prevent valid input, frustrating users by clearing acceptable characters.

Balance strictness with usability by iteratively refining your regex pattern to allow legitimate variations.

Neglecting Validation Event Handling

Failing to subscribe to the ValidationFailed event might leave you unaware of recurring invalid input issues that could degrade data quality.

Implement robust logging or UI feedback in the ValidationFailed event to monitor and address input issues as they occur.


Usage Scenarios

Scenario
Description
Implementation Example

Numeric-Only Code Entry

Ensuring that only digits are entered, such as in PIN or OTP fields, to avoid errors during numerical processing.

Set the ValidationPattern to match digits only (e.g., "^[0-9]+$") and enable StrictValidation.

Alphanumeric Code Validation

Validating that the entered code consists solely of alphanumeric characters, which is common in serial keys or registration codes.

Set ValidationPattern to "^[A-Za-z0-9]+$" and enable StrictValidation to filter out any non-alphanumeric characters.

Handling Invalid Input Gracefully

Providing immediate feedback when an invalid character is entered, so the user is aware that their input is being rejected.

Subscribe to the ValidationFailed event to notify the user or log the incident when invalid characters are cleared automatically.


Code Examples

Example 1: Enforcing Numeric-Only Input

// Create an instance of the control
SiticoneOtp otpControl = new SiticoneOtp();

// Set the ValidationPattern to allow only digits
otpControl.ValidationPattern = "^[0-9]+$";

// Enable strict validation so invalid characters are cleared immediately
otpControl.StrictValidation = true;

// Add the control to your form
this.Controls.Add(otpControl);
otpControl.Location = new Point(50, 50);

// Optionally subscribe to the ValidationFailed event for logging
otpControl.ValidationFailed += (sender, e) =>
{
    foreach (var invalidChar in e.InvalidCharacters)
    {
        Console.WriteLine($"Invalid character at index {invalidChar.Index}: {invalidChar.Value}");
    }
};

Example 2: Allowing Alphanumeric Input

// Create an instance of the control
SiticoneOtp otpControl = new SiticoneOtp();

// Set the ValidationPattern to allow only letters and digits
otpControl.ValidationPattern = "^[A-Za-z0-9]+$";

// Enable strict validation to automatically clear invalid input
otpControl.StrictValidation = true;

// Add the control to the form
this.Controls.Add(otpControl);
otpControl.Location = new Point(50, 120);

// Subscribe to the InputCompleted event to process the entered code
otpControl.InputCompleted += (sender, e) =>
{
    Console.WriteLine($"Completed code: {e.EnteredCodeAsString}");
};

Example 3: Customizing and Handling Invalid Input

// Create an instance of the control
SiticoneOtp otpControl = new SiticoneOtp();

// Customize the validation pattern (e.g., hexadecimal characters)
otpControl.ValidationPattern = "^[0-9A-Fa-f]+$";

// Enable strict validation for immediate feedback on invalid input
otpControl.StrictValidation = true;

// Add the control to your form
this.Controls.Add(otpControl);
otpControl.Location = new Point(50, 190);

// Handle validation failures to provide user feedback
otpControl.ValidationFailed += (sender, e) =>
{
    foreach (var invalidChar in e.InvalidCharacters)
    {
        // Example: Display an error message to the user
        MessageBox.Show($"Invalid character '{invalidChar.Value}' at position {invalidChar.Index}. Please use hexadecimal characters only.", "Input Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
};

Review

Aspect
Evaluation

Robustness

The input validation mechanism effectively ensures that only permitted characters are accepted, significantly reducing the risk of invalid data entry.

Developer Flexibility

By allowing custom regex patterns and enabling strict validation, developers have fine-grained control over the allowed input, making it adaptable to various use cases.

Real-Time Feedback

Automatic triggering of the ValidationFailed event provides immediate feedback for troubleshooting and enhances the overall user experience.


Summary

Input Validation in the SiticoneOtp control is a comprehensive feature that uses regular expressions to enforce data integrity. With customizable validation patterns and a strict validation mode, it automatically clears invalid input and raises detailed events, enabling developers to maintain high standards of data quality while offering real-time feedback to users.


Additional Recommendations

Recommendation
Explanation

Regularly Update Regex Patterns

As application requirements evolve, review and update your validation patterns to ensure they remain aligned with your current input criteria.

Combine with Interactive Feedback

Use interactive feedback (shake and beep) in tandem with validation events to provide both immediate visual and auditory cues when invalid input is detected.

Extensive Testing Across Scenarios

Test your validation rules in a variety of scenarios to ensure that the control handles edge cases gracefully and provides a consistent user experience.

Document Validation Rules for End Users

Clearly communicate the expected input format to users (via tooltips, help texts, etc.) to minimize errors and improve overall data entry success.

Last updated