Does anyone have a good solution for validating UI input in Maui?
The only real solution I saw was the validation in the community toolkit, but that doesn't even work, so looking for someone to advise on what to do...
Thanks
CodePudding user response:
There are few ways to make such validation.
One way is using inheriting ObservableValidator.
public partial class MainViewModel : ObservableValidator
{
[Required(ErrorMessage = "Text is Required Field!")]
[MinLength(5,ErrorMessage = "Text length is minimum 5!")]
[MaxLength(10, ErrorMessage = "Text length is maximum 10!")]
[ObservableProperty]
string _text = "Hello";
[ObservableProperty]
bool _isTextValid;
[ObservableProperty]
string _error;
[RelayCommand]
void Validate()
{
ValidateAllProperties();
if (HasErrors)
Error = string.Join(Environment.NewLine, GetErrors().Select(e => e.ErrorMessage));
else
Error = String.Empty;
IsTextValid = (GetErrors().ToDictionary(k => k.MemberNames.First(), v => v.ErrorMessage) ?? new Dictionary<string, string?>()).TryGetValue(nameof(Text), out var error);
}
}
This is the way you can do it in your ViewModel.
The second way is using behaviors.
<Entry.Behaviors>
<toolkit:EmailValidationBehavior InvalidStyle="{StaticResource InvalidEntryStyle}"
IsValid="{Binding EmailIsValid}"
ValidStyle="{StaticResource NormalEntryStyle}"
Flags="ValidateOnValueChanged" >
</toolkit:EmailValidationBehavior>
</Entry.Behaviors>
This is how I do it with the XAML.
I use both, depending on what I want to do.