---
description: >-
  This feature provides a built‐in mechanism to validate phone number input and
  notify developers of the input’s validity through events and read-only
  properties.
---

# Input Validation

## Overview

The Input Validation feature consists of several public properties and events that allow developers to enforce custom validation rules for the phone number input. The control automatically validates the input and exposes both the validation result and any error message.

| Property / Event         | Type                         | Default          | Description                                                                                       |
| ------------------------ | ---------------------------- | ---------------- | ------------------------------------------------------------------------------------------------- |
| ValidationFunction       | Func\<string, bool>          | null             | A delegate that validates the phone number input; returns true if valid and false otherwise.      |
| ValidationErrorMessage   | string                       | "Invalid input." | A message that explains why the input did not pass validation.                                    |
| Validated                | event ValidationEventHandler | N/A              | An event raised after validation is performed, allowing developers to handle validation outcomes. |
| IsValid (read-only)      | bool                         | true             | Indicates whether the current input passes the defined validation function.                       |
| ErrorMessage (read-only) | string                       | string.Empty     | Contains the error message associated with the last validation attempt if the input was invalid.  |

***

### Key Points

| Aspect                    | Detail                                                                                                            |
| ------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Custom Validation         | Developers can assign their own function to ValidationFunction to enforce business rules or formatting standards. |
| Immediate Feedback        | Validation is triggered on input changes, and the control automatically updates IsValid and ErrorMessage.         |
| Event-Driven Notification | The Validated event allows additional logic to be executed after the input is validated.                          |

***

### Best Practices

| Practice                                 | Explanation                                                                                                                         |
| ---------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| Implement Comprehensive Validation       | Ensure that your ValidationFunction covers all edge cases, such as proper formatting, required country code, and valid digit count. |
| Provide Meaningful Error Messages        | Set a clear and descriptive ValidationErrorMessage so that users understand why their input was rejected.                           |
| Subscribe to the Validated Event         | Use the Validated event to trigger UI updates or error notifications based on the validation outcome.                               |
| Avoid Complex Operations in the Delegate | Keep the ValidationFunction lightweight to maintain a responsive UI; offload any heavy processing as needed.                        |

***

### Common Pitfalls

| Pitfall                                   | How to Avoid                                                                                                      |
| ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| Not Updating the UI on Validation Failure | Always subscribe to the Validated event to update error displays or visual cues when input is invalid.            |
| Overly Permissive Validation Function     | Ensure that the ValidationFunction correctly handles empty strings, non-digit characters, and unexpected formats. |
| Ignoring the ValidationErrorMessage       | Set and utilize the ValidationErrorMessage to provide clear feedback to end users instead of leaving it blank.    |

***

### Usage Scenarios

| Scenario                        | Example Use Case                                                                                                           |
| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| Enforcing International Formats | Validate that international numbers include the correct country code and formatting using a custom ValidationFunction.     |
| Local Phone Number Verification | Configure validation logic to ensure that local phone numbers adhere to national formatting rules.                         |
| Real-Time Input Feedback        | Use the Validated event to update UI elements (such as error labels or border colors) immediately after input is modified. |

***

### Code Examples

Example 1: Basic Validation Setup\
This sample shows how to configure a simple validation function that ensures the phone number contains exactly 10 digits.

```csharp
// Create an instance of the phone number box control
SiticonePhoneNumberBox phoneNumberBox = new SiticonePhoneNumberBox();

// Define a simple validation function: valid if exactly 10 digits are present
phoneNumberBox.ValidationFunction = (input) =>
{
    // Remove non-digit characters
    string digitsOnly = new string(input.Where(char.IsDigit).ToArray());
    return digitsOnly.Length == 10;
};

// Set a custom error message
phoneNumberBox.ValidationErrorMessage = "The phone number must contain exactly 10 digits.";

// Subscribe to the Validated event to handle validation outcomes
phoneNumberBox.Validated += (sender, args) =>
{
    if (!args.IsValid)
    {
        // For example, display the error message in a label
        errorLabel.Text = args.ErrorMessage;
    }
    else
    {
        errorLabel.Text = string.Empty;
    }
};

// Set location and size, then add the control to the form
phoneNumberBox.Location = new Point(20, 20);
phoneNumberBox.Size = new Size(250, 40);
this.Controls.Add(phoneNumberBox);
```

Example 2: Advanced Validation with Multiple Conditions\
This example demonstrates a more complex validation function that checks for a valid country code prefix along with digit count.

```csharp
// Assume the control is already instantiated
phoneNumberBox.ValidationFunction = (input) =>
{
    // Example: For international format, require a '+' sign and at least 11 digits
    if (input.StartsWith("+"))
    {
        string digitsOnly = new string(input.Where(char.IsDigit).ToArray());
        return digitsOnly.Length >= 11;
    }
    // For national format, require exactly 10 digits
    else
    {
        string digitsOnly = new string(input.Where(char.IsDigit).ToArray());
        return digitsOnly.Length == 10;
    }
};

// Set a corresponding error message
phoneNumberBox.ValidationErrorMessage = "Invalid phone number. Ensure it includes a valid country code for international numbers or exactly 10 digits for local numbers.";

// Subscribe to the Validated event to react to validation outcomes
phoneNumberBox.Validated += (sender, args) =>
{
    if (!args.IsValid)
    {
        // Highlight the control or show a tooltip with the error message
        phoneNumberBox.BackColor = Color.MistyRose;
    }
    else
    {
        phoneNumberBox.BackColor = Color.White;
    }
};
```

Example 3: Handling Validation State in Real-Time\
This sample illustrates how to retrieve the current validation status and error message at any point.

```csharp
// Button click event to check the current validation state
private void CheckValidationButton_Click(object sender, EventArgs e)
{
    if (phoneNumberBox.IsValid)
    {
        MessageBox.Show("Phone number is valid.");
    }
    else
    {
        MessageBox.Show($"Phone number is invalid: {phoneNumberBox.ErrorMessage}");
    }
}
```

***

### Review

| Aspect             | Review Comment                                                                                                      |
| ------------------ | ------------------------------------------------------------------------------------------------------------------- |
| Customizability    | The ValidationFunction property offers flexible customization to enforce diverse business rules.                    |
| Immediate Feedback | The Validated event and read-only properties (IsValid, ErrorMessage) provide real-time feedback on user input.      |
| Integration Ease   | Code examples demonstrate straightforward integration with common UI update scenarios based on validation outcomes. |

***

### Summary

The Input Validation feature of the SiticonePhoneNumberBox control enables developers to enforce custom validation rules for phone number input. By leveraging the ValidationFunction, ValidationErrorMessage, and Validated event, developers can provide immediate and clear feedback to users, ensuring that input conforms to the required formats and standards.

***

### Additional Notes

| Note Type     | Detail                                                                                                                                |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| Extensibility | The ValidationFunction can be extended to support complex validation scenarios, including regex checks and multi-condition logic.     |
| UI Feedback   | Combine the Input Validation feature with visual customizations (e.g., border color changes, error labels) for a cohesive experience. |
| Debugging     | Use the ErrorMessage property during development to troubleshoot and fine-tune the validation logic as needed.                        |







