我正在寻找用于表单验证的优雅解决方案。
我找到了这个Validation in Enterprise Apps,但不适用于类。
当前解决方案:
public class ItemModel
{
[Required]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
public class NewItemViewModel : BaseViewModel
{
private ValidatableObject<string> _userName = new ValidatableObject<string>();
public ValidatableObject<string> UserName
{
get => _userName;
set => SetProperty(ref _userName, value);
}
private ValidatableObject<string> _password = new ValidatableObject<string>();
public ValidatableObject<string> Password
{
get => _password;
set => SetProperty(ref _password, value);
}
public NewItemViewModel()
{
AddValidations();
}
public void Save(){
var itemModel = new ItemModel { UserName = UserName.Value, Password = Password.Value };
//TODO do something
}
private void AddValidations()
{
_userName.ValidationRules.Add(new IsNotNullOrEmptyRule<string> { ValidationMessage = "A username is required." });
_password.ValidationRules.Add(new IsNotNullOrEmptyRule<string> { ValidationMessage = "A password is required." });
}
}
我只想在Model上指定验证,并且能够通过View,ViewModel中的字段进行检查。
我这样做了,但是它仍然是视图的模型。
优点是验证链接到模型而不是视图。
有必要将模型转换为背面。
public class ItemModel : ObservableObject
{
private ValidatableObject<string> _userName = new ValidatableObject<string>();
public ValidatableObject<string> UserName
{
get => _userName;
set => SetProperty(ref _userName, value);
}
private ValidatableObject<string> _password = new ValidatableObject<string>();
public ValidatableObject<string> Password
{
get => _password;
set => SetProperty(ref _password, value);
}
public ItemModel(string userName, string password)
{
UserName.Value = userName;
Password.Value = password;
AddValidations();
}
public bool Validate()
{
var isValidUserName = ValidateUserName();
var isValidPassword = ValidatePassword();
return isValidUserName && isValidPassword;
}
public bool ValidateUserName()
{
return _userName.Validate();
}
public bool ValidatePassword()
{
return _password.Validate();
}
private void AddValidations()
{
_userName.ValidationRules.Add(new IsNotNullOrEmptyRule<string> { ValidationMessage = "A username is required." });
_password.ValidationRules.Add(new IsNotNullOrEmptyRule<string> { ValidationMessage = "A password is required." });
}
}
public class NewItemViewModel : BaseViewModel
{
public ItemModel ItemModel { get; set; }
public NewItemViewModel()
{
Title = "New ItemModel";
ItemModel = new ItemModel("Username", "P@ssword");
}
public ICommand SaveCommand => new AsyncCommand(Save);
private async Task Save()
{
if (ItemModel.Validate())
{
var itemModel = new ItemModel(ItemModel.UserName.Value, ItemModel.Password.Value);
await Application.Current.MainPage.DisplayAlert("Item", $"{itemModel.UserName} {itemModel.Password}", "Ok");
}
}
public ICommand ValidateUserNameCommand => new Command(() => ItemModel.ValidateUserName());
public ICommand ValidatePasswordCommand => new Command(() => ItemModel.ValidatePassword());
}