0

I have a Maui app with a view model. The ViewModel has the following property:

[ObservableProperty]
public UserAccountDTO userAccount = new UserAccountDTO();

UserAccountDTO has the following property:

   public partial class UserAccountDTO: ObservableValidator
    {
        [Required(AllowEmptyStrings = false, ErrorMessage = "Firstname required")]
        [MaxLength(10, ErrorMessage = "Text length is maximum 10!")]
        [ObservableProperty]
        public string firstName;
    }

I have the firstName bound to an Entry.

In the VM, when I call ValidateAllProperties() I don't get any errors coming back from this class. I.e. if FirstName is blank HasErrors is still false.

[RelayCommand]
private async void CreateAccountPressed()
{
    ValidateAllProperties();
    string Error = string.Empty;

    if (HasErrors)
            Error = string.Join(Environment.NewLine, GetErrors().Select(e => e.ErrorMessage));
}  

Am I missing something?

Thanks

BuckBuchanan
  • 198
  • 13

2 Answers2

0

If you want to set the ObservableValidator for the firstName, you should add the get and set method to the Firstname.

[Required(AllowEmptyStrings = false, ErrorMessage = "Firstname required")]
[MaxLength(10, ErrorMessage = "Text length is maximum 10!")]
[ObservableProperty]
  public string FirstName
    {
        get => this.firstName;
        set => SetProperty(ref this.firstName, value, true);
    }
Guangyu Bai - MSFT
  • 2,555
  • 1
  • 2
  • 8
0

I have same issue, I only found this on github.

"You're trying to validate TestViewModel, but this type has no validatable properties. Validation doesn't automatically handle nested properties, you'll have to either call the validation on both nested properties manually and forward the errors, or write some custom attribute that will implement the validation for a nested viewmodel. The fact you're currently not seeing errors is expected "

https://github.com/CommunityToolkit/dotnet/discussions/557

Noob
  • 710
  • 11
  • 15