SignUpViewModel.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.ComponentModel;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq;
  5. using CommunityToolkit.Mvvm.ComponentModel;
  6. using CommunityToolkit.Mvvm.Input;
  7. namespace Generators.Sandbox.ViewModels;
  8. public class SignUpViewModel : ObservableValidator
  9. {
  10. public SignUpViewModel()
  11. {
  12. UserName = "Joseph!";
  13. Password = "1234";
  14. ConfirmPassword = "1234";
  15. SignUp = new RelayCommand(() => { }, () => !HasErrors);
  16. ErrorsChanged += OnErrorsChanged;
  17. }
  18. public RelayCommand SignUp { get; }
  19. [Required]
  20. public string? UserName {
  21. get;
  22. set => SetProperty(ref field, value, validate: true);
  23. }
  24. public string? UserNameValidation
  25. => GetValidationMessage(nameof(UserName));
  26. [Required]
  27. [MinLength(2)]
  28. public string? Password
  29. {
  30. get;
  31. set
  32. {
  33. if (SetProperty(ref field, value, validate: true))
  34. ValidateProperty(ConfirmPassword, nameof(ConfirmPassword));
  35. }
  36. }
  37. public string? PasswordValidation
  38. => GetValidationMessage(nameof(Password));
  39. [Required]
  40. [Compare(nameof(Password))]
  41. public string? ConfirmPassword
  42. {
  43. get;
  44. set => SetProperty(ref field, value, validate: true);
  45. }
  46. public string? ConfirmPasswordValidation
  47. => GetValidationMessage(nameof(ConfirmPassword));
  48. public string? CompoundValidation
  49. => GetValidationMessage(null);
  50. private void OnErrorsChanged(object? sender, DataErrorsChangedEventArgs e)
  51. {
  52. if (e.PropertyName is not null)
  53. OnPropertyChanged(e.PropertyName + "Validation");
  54. OnPropertyChanged(CompoundValidation);
  55. SignUp.NotifyCanExecuteChanged();
  56. }
  57. private string? GetValidationMessage(string? propertyName)
  58. {
  59. var message = string.Join(Environment.NewLine, GetErrors(propertyName).Select(v => v.ErrorMessage));
  60. return string.IsNullOrEmpty(message) ? null : message;
  61. }
  62. }