# Input and Validation

## Overview

The Input & Validation feature of the SiticoneCardNumberBox control exposes properties and events that let you enforce custom validation rules. Developers can specify a validation function that processes the current text, provide an error message to display when validation fails, and subscribe to validation events. The control also maintains read‑only properties indicating the current validation status and error details. This feature ensures that only valid input is processed further.

***

### Property and Event Details

The table below summarizes the key properties and events related to input validation:

<table><thead><tr><th width="227">Property / Event</th><th>Description</th><th>Default Value / Notes</th></tr></thead><tbody><tr><td>ValidationFunction</td><td>A custom function that returns a Boolean indicating whether the input is valid.</td><td>Null by default; user-supplied function</td></tr><tr><td>ValidationErrorMessage</td><td>The error message to display when the input does not pass validation.</td><td>"Invalid input." (or user-defined)</td></tr><tr><td>Validated (event)</td><td>Event that is raised after the input has been validated.</td><td>Use to update the UI or handle errors accordingly</td></tr><tr><td>IsValid</td><td>Read-only property indicating whether the current input is valid.</td><td>True when no validation issues; otherwise false</td></tr><tr><td>ErrorMessage</td><td>Read-only property providing the current validation error message, if any.</td><td>Empty string if input is valid</td></tr></tbody></table>

***

### Code Examples

#### Example 1: Setting Up a Custom Validation Function

This example demonstrates how to implement a custom validation function that checks if the input contains only numeric characters and has a minimum length.

```csharp
// Create an instance of the SiticoneCardNumberBox control
SiticoneCardNumberBox cardNumberBox = new SiticoneCardNumberBox();

// Define a custom validation function that ensures the input is numeric and at least 12 digits long
cardNumberBox.ValidationFunction = (input) =>
{
    string digitsOnly = new string(input.Where(char.IsDigit).ToArray());
    return digitsOnly.Length >= 12;
};

// Set a custom error message for failed validations
cardNumberBox.ValidationErrorMessage = "Please enter at least 12 numeric digits.";

// Subscribe to the Validated event to handle validation feedback
cardNumberBox.Validated += (sender, e) =>
{
    if (!e.IsValid)
    {
        Console.WriteLine("Validation failed: " + e.ErrorMessage);
        // Update UI components, e.g., display an error label
    }
    else
    {
        Console.WriteLine("Input is valid.");
    }
};

// Add the control to your form
this.Controls.Add(cardNumberBox);
cardNumberBox.Location = new Point(20, 20);
cardNumberBox.Size = new Size(300, 50);
```

#### Example 2: Handling Validation Status in Your Application

This example shows how to read the validation status and error message properties after the user updates the input.

```csharp
// Assume cardNumberBox is an instance of SiticoneCardNumberBox on the form

// In an event handler (e.g., a button click) check validation status:
private void SubmitButton_Click(object sender, EventArgs e)
{
    if (cardNumberBox.IsValid)
    {
        // Proceed with submission
        Console.WriteLine("Submitting valid card number: " + cardNumberBox.FormattedCardNumber);
    }
    else
    {
        // Alert the user to the validation issue
        MessageBox.Show("Error: " + cardNumberBox.ErrorMessage, "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
    }
}
```

***

### Key Points

The table below highlights the key aspects of the Input & Validation feature:

<table><thead><tr><th width="229">Topic</th><th>Description</th></tr></thead><tbody><tr><td>Custom Validation Logic</td><td>Use the ValidationFunction to implement tailored rules for acceptable input.</td></tr><tr><td>Immediate Feedback</td><td>The Validated event and IsValid property offer immediate insight into whether input is correct.</td></tr><tr><td>Error Messaging</td><td>A user-friendly error message is provided via ValidationErrorMessage when validation fails.</td></tr></tbody></table>

***

### Best Practices

The table below outlines best practices for implementing input validation:

<table><thead><tr><th width="340">Best Practice</th><th>Explanation</th></tr></thead><tbody><tr><td>Define clear validation criteria</td><td>Ensure your validation function is specific and well-tested to avoid ambiguous input rejections.</td></tr><tr><td>Provide a user-friendly error message</td><td>Use ValidationErrorMessage to offer actionable feedback that informs users how to correct their input.</td></tr><tr><td>Always subscribe to the Validated event</td><td>Use the event to update UI elements in real time and provide visual cues to guide the user.</td></tr><tr><td>Test with different inputs</td><td>Validate a wide range of inputs (e.g., valid, invalid, edge cases) to ensure robustness of your function.</td></tr></tbody></table>

***

### Common Pitfalls

The table below lists common pitfalls and how to avoid them:

<table><thead><tr><th width="364">Pitfall</th><th>How to Avoid It</th></tr></thead><tbody><tr><td>Overly strict validation logic</td><td>Ensure the validation function accounts for real-world input variations and does not reject valid cases.</td></tr><tr><td>Not providing an error message</td><td>Always assign a meaningful message to ValidationErrorMessage to aid user correction.</td></tr><tr><td>Failing to subscribe to the Validated event</td><td>Ensure event subscriptions are in place so that UI updates reflect the current validation state promptly.</td></tr><tr><td>Ignoring the IsValid property in subsequent processing</td><td>Always check IsValid before proceeding with processing to avoid using invalid input.</td></tr></tbody></table>

***

### Usage Scenarios

The table below describes several scenarios where input validation is essential:

<table><thead><tr><th width="283">Scenario</th><th>Description</th></tr></thead><tbody><tr><td>Payment form input verification</td><td>Ensures that the credit card number or other sensitive data meets the required format before submission.</td></tr><tr><td>User registration forms</td><td>Validate email addresses, phone numbers, or other text input using a custom validation function.</td></tr><tr><td>Data entry applications</td><td>Confirm that each field meets its validation criteria to prevent errors and maintain data integrity.</td></tr></tbody></table>

***

### Real Life Usage Scenarios

<table><thead><tr><th width="278">Scenario</th><th>Example</th></tr></thead><tbody><tr><td>E-commerce checkout process</td><td>Validate credit card numbers to ensure the proper format before processing payments.</td></tr><tr><td>Mobile banking applications</td><td>Confirm that entered account numbers or identification codes are valid using custom validation logic.</td></tr><tr><td>Subscription services</td><td>Enforce strict validation on recurring payment data to minimize the risk of billing errors.</td></tr></tbody></table>

***

### Troubleshooting Tips

The table below provides troubleshooting advice for common validation issues:

| Issue                            | Potential Cause                                                       | Recommended Action                                                   |
| -------------------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------- |
| Validation always fails          | The validation function might be too strict or not handle edge cases. | Debug the ValidationFunction and test with a variety of inputs.      |
| No error message is shown        | ValidationErrorMessage may not be set properly.                       | Set a clear and descriptive error message in ValidationErrorMessage. |
| Validated event is not triggered | Event subscription might be missing or removed inadvertently.         | Verify that the Validated event is properly subscribed in your code. |

***

### Review

The table below provides a summary review of the Input & Validation feature:

<table><thead><tr><th width="166">Aspect</th><th>Review Notes</th></tr></thead><tbody><tr><td>Customization</td><td>The use of a custom validation function provides flexibility for various input scenarios.</td></tr><tr><td>User Feedback</td><td>Real-time validation feedback and error messages enhance the user experience.</td></tr><tr><td>Integration</td><td>Easy-to-use properties and events allow seamless integration into existing form validation workflows.</td></tr></tbody></table>

***

### Summary

The Input & Validation feature of the SiticoneCardNumberBox control empowers developers to enforce custom input rules and provide immediate feedback. With properties such as ValidationFunction, ValidationErrorMessage, and read-only indicators like IsValid and ErrorMessage, this feature ensures that only valid input is processed further. The associated events allow real-time UI updates, making it a robust solution for data entry forms and payment interfaces.

***

### Additional Integration Example

Below is a complete integration example that combines input validation with visual feedback in a WinForms application:

```csharp
public partial class InputValidationForm : Form
{
    public InputValidationForm()
    {
        InitializeComponent();
        InitializeCardInputWithValidation();
    }

    private void InitializeCardInputWithValidation()
    {
        // Create and configure the card number box
        SiticoneCardNumberBox cardNumberBox = new SiticoneCardNumberBox
        {
            Location = new Point(20, 20),
            Size = new Size(350, 60),
            ValidationFunction = (input) =>
            {
                // Ensure input is numeric and at least 12 digits long
                string digitsOnly = new string(input.Where(char.IsDigit).ToArray());
                return digitsOnly.Length >= 12;
            },
            ValidationErrorMessage = "Enter at least 12 numeric digits."
        };

        // Subscribe to the Validated event to update the UI
        cardNumberBox.Validated += (sender, e) =>
        {
            if (!e.IsValid)
            {
                // For example, update a label with the error message
                errorLabel.Text = e.ErrorMessage;
                errorLabel.ForeColor = Color.Red;
            }
            else
            {
                errorLabel.Text = string.Empty;
            }
        };

        // Add the control and an error label to the form
        this.Controls.Add(cardNumberBox);
        Label errorLabel = new Label
        {
            Location = new Point(20, 90),
            Size = new Size(350, 20)
        };
        this.Controls.Add(errorLabel);
    }
}
```

***

By following this documentation, developers can effectively implement and integrate input validation into their applications using the SiticoneCardNumberBox control. The combination of custom validation functions, error messaging, and event notifications makes it easy to ensure that user input meets the required standards before processing.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs-siticoneframework.gitbook.io/home/net-framework-or-net-core-ui/special-purpose-controls/siticone-cardnumber/input-and-validation.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
