根据模型验证 ASP.NET MVC2 FormCollection
假设我有一个带有如下验证的用户类设置:
[MetadataType(typeof(ssUserMetaData))]
public partial class ssUser
{
}
class ssUserMetaData
{
[Required(ErrorMessage = "Name is a required field.")]
[StringLength(100, ErrorMessage = "Name must be 100 characters or less.")]
public string Name { get; set; }
[Required(ErrorMessage = "Username is a required field.")]
[StringLength(50, ErrorMessage = "Username must be 50 characters or less.")]
public string Username { get; set; }
[Required(ErrorMessage = "Email address is a required field.")]
[Email(ErrorMessage = "Email address must be a valid format.")]
[StringLength(100, ErrorMessage = "Email address must be 100 characters or less.")]
[DisplayName("Email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is a required field.")]
[StringLength(1000, MinimumLength = 6, ErrorMessage = "Passwords must be at least 6 characters long.")]
[DisplayName("Password")]
public string PasswordHash { get; set; }
}
现在,我有一个更新方法,仅允许用户更新几个字段,例如“姓名”和“电子邮件”。我不想重新提交此表单的所有数据以传递模型绑定,但我想使用此处配置的验证规则来检查表单集合中的特定值。
像这样的想象中的代码...
bool result = ModelState.ValidateField("Email", formCollection["Email"]);
有没有办法做这样的事情,这样我就可以避免重复我的验证规则?谢谢!
Let's say I have a user class setup with validation like this:
[MetadataType(typeof(ssUserMetaData))]
public partial class ssUser
{
}
class ssUserMetaData
{
[Required(ErrorMessage = "Name is a required field.")]
[StringLength(100, ErrorMessage = "Name must be 100 characters or less.")]
public string Name { get; set; }
[Required(ErrorMessage = "Username is a required field.")]
[StringLength(50, ErrorMessage = "Username must be 50 characters or less.")]
public string Username { get; set; }
[Required(ErrorMessage = "Email address is a required field.")]
[Email(ErrorMessage = "Email address must be a valid format.")]
[StringLength(100, ErrorMessage = "Email address must be 100 characters or less.")]
[DisplayName("Email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is a required field.")]
[StringLength(1000, MinimumLength = 6, ErrorMessage = "Passwords must be at least 6 characters long.")]
[DisplayName("Password")]
public string PasswordHash { get; set; }
}
Now, I have an update method that only allows users to update a couple fields, like Name and Email. I don't want to resubmit all of the data for this form to pass model binding, but I would like to use the validation rules configured here to check against a specific value in the form collection.
Something like this imaginary code...
bool result = ModelState.ValidateField("Email", formCollection["Email"]);
Is there a way do do something like this so I can avoid repeating my validation rules? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
让小表单使用 NameAndEmail 类而大表单使用 SsUserMetaData 怎么样?
What about having the small form use the NameAndEmail class and the large form use SsUserMetaData?