Search code examples
c#community-toolkit-mvvm

How can I get if there is an error in a certain property via ObservableValidator?


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?


Solution

  • 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:

    1. Install the nuget package CommunityToolkit.Maui.
    2. Initialize the package in your MauiProgram.cs builder.UseMauiCommunityToolkit().
    3. Add MAUI community toolkit xaml namespace where it is used: 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.