Validation in .NET MAUI Masked Entry
21 Jul 20264 minutes to read
The SfMaskedEntry control validates user input against the configured Mask and exposes the result through the HasError property. Use the ValidationMode property to choose when validation is performed.
Prerequisites
Before using the SfMaskedEntry, ensure the following NuGet package is installed in your .NET MAUI project:
Syncfusion.Maui.Inputs
For a step-by-step setup, refer to the Getting Started documentation.
Validation Mode
Use the ValidationMode property of type InputValidationMode to choose when the input is validated. The available enum values are:
-
KeyPress: validation is triggered for each key press. -
LostFocus: validation is performed only when the control loses focus.
The default value is KeyPress. The selected mode works the same for both Simple and RegEx MaskType values.
<editors:SfMaskedEntry x:Name="maskedEntry"
WidthRequest="200"
MaskType="Simple"
Mask="00/00/0000"
ValidationMode="KeyPress"/>SfMaskedEntry maskedEntry = new SfMaskedEntry
{
WidthRequest = 200,
MaskType = MaskedEntryMaskType.Simple,
Mask = "00/00/0000",
ValidationMode = InputValidationMode.KeyPress
};HasError
The HasError property of type bool indicates the result of the most recent validation. It is a read-only property that returns true when validation fails and false when validation succeeds. The property is updated only after a ValueChanged event, so check it inside the event handler (or use a Binding to react to the change in MVVM scenarios).
The following example shows how to surface the validation result in the UI.
<VerticalStackLayout>
<editors:SfMaskedEntry x:Name="maskedEntry"
WidthRequest="200"
MaskType="Simple"
Mask="00/00/0000"
ValueChanged = "MaskedEntry_ValueChanged"
ValidationMode="LostFocus"/>
<Label Text="Please enter a valid date."
TextColor="Red"
IsVisible="{Binding HasError, Source={x:Reference maskedEntry}}"/>
</VerticalStackLayout>SfMaskedEntry maskedEntry = new SfMaskedEntry
{
WidthRequest = 200,
MaskType = MaskedEntryMaskType.Simple,
Mask = "00/00/0000",
ValidationMode = InputValidationMode.LostFocus
};
maskedEntry.ValueChanged += MaskedEntry_ValueChanged;private void MaskedEntry_ValueChanged(object sender, MaskedEntryValueChangedEventArgs e)
{
if (sender is SfMaskedEntry entry && entry.HasError)
{
var page = Application.Current?.Windows[0]?.Page;
page?.DisplayAlert("Alert", "Please enter valid details", "OK");
}
}The following image illustrates an invalid input that triggers HasError = true:
