I am using the CommunityToolkit.Mvvm(https://learn.microsoft.com/en-us/dotnet/communitytoolkit/mvvm/) now.
There is some properties that I validate by ValidationAttribute, for example:
string _RemoteIP = "";
[IPAddress]
public string RemoteIP
{
get => _RemoteIP;
set
{
if (_RemoteIP != value)
{
_RemoteIP = value;
OnPropertyChanged();
ValidateProperty(RemoteIP);
}
}
}
public sealed class IPAddressAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
string _pattern = @"^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$";
if (value is string _string && Regex.IsMatch(_string, _pattern))
{
return ValidationResult.Success;
}
return new("InvalidIPAddress");
}
}
For some reason, when the user clicks the sumbmit button, I need to get if some property has errors (but not if all the properties have errors).
How can I implement this?
An alternative is using TextValidationBehavior from MAUI community toolkit package.
<Entry Text="{Binding RemoteIP}">
<Entry.Behaviors>
<xct:TextValidationBehavior Flags="ValidateOnValueChanged"
InvalidStyle="{StaticResource InvalidEntryStyle}"
RegexOptions="IgnoreCase"
RegexPattern="^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$"
ValidStyle="{StaticResource ValidEntryStyle}" />
</Entry.Behaviors>
</Entry>
Get started with CommunityToolkit.Maui:
CommunityToolkit.Maui
.builder.UseMauiCommunityToolkit()
.xmlns:xct="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
You can control when the validation is triggered with the Flags
property in the above example it will trigger upon value changed of RemoteIP
property.
You can also force/Invoke the validation from code, for example upon button clicked event:
private void OnCounterClicked(object sender, EventArgs e)
{
var validator = (TextValidationBehavior)entry.Behaviors.First(x => x is TextValidationBehavior);
validator?.ForceValidate();
}
In this case you might want to set the Flags
property to None
.
Ps: You need to define styles ValidEntryStyle
InValidEntryStyle
used in sample above, sample in the docs.