1)在从用户那里检索信息的模型上使用流利的验证。它比数据注释更灵活,更容易测试。
2)您可能想通过使用 automapper 来研究 automapper,您不必编写x.name = y.name
.
3)对于您的数据库模型,我会坚持使用数据注释。
以下所有内容均基于新信息
首先,您应该像现在对实际模型验证所做的那样在这两个位置进行验证,这就是我将这样做的方式。免责声明:这不是完美的方式
首先更新UserViewModel
到
public class UserViewModel
{
[Required()]
[RegularExpression(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$")]
public String Email { get; set; }
}
然后将动作方法更新为
// Post action
[HttpPost]
public ActionResult register (UserViewModel uvm)
{
// This validates the UserViewModel
if (ModelState.IsValid)
{
try
{
// You should delegate this task to a service but to keep it simple we do it here
User u = new User() { Email = uvm.Email, Created = DateTime.Now };
RedirectToAction("Index"); // On success you go to other page right?
}
catch (Exception x)
{
ModelState.AddModelError("RegistrationError", x); // Replace x with your error message
}
}
// Return your UserViewModel to the view if something happened
return View(uvm);
}
现在对于用户模型,它变得棘手,您有许多可能的解决方案。我想出的解决方案(可能不是最好的)如下:
public class User
{
private string email;
private DateTime created;
public string Email
{
get
{
return email;
}
set
{
email = ValidateEmail(value);
}
}
private string ValidateEmail(string value)
{
if (!validEmail(value))
throw new NotSupportedException("Not a valid email address");
return value;
}
private bool validEmail(string value)
{
return Regex.IsMatch(value, @"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$");
}
最后一些单元测试来检查我自己的代码:
[TestClass()]
public class UserTest
{
/// <summary>
/// If the email is valid it is stored in the private container
/// </summary>
[TestMethod()]
public void UserEmailGetsValidated()
{
User x = new User();
x.Email = "test@test.com";
Assert.AreEqual("test@test.com", x.Email);
}
/// <summary>
/// If the email is invalid it is not stored and an error is thrown in this application
/// </summary>
[TestMethod()]
[ExpectedException(typeof(NotSupportedException))]
public void UserEmailPropertyThrowsErrorWhenInvalidEmail()
{
User x = new User();
x.Email = "blah blah blah";
Assert.AreNotEqual("blah blah blah", x.Email);
}
/// <summary>
/// Clears an assumption that on object creation the email is validated when its set
/// </summary>
[TestMethod()]
public void UserGetsValidatedOnConstructionOfObject()
{
User x = new User() { Email = "test@test.com" };
x.Email = "test@test.com";
Assert.AreEqual("test@test.com", x.Email);
}
}