开发者

Validating ASP.NET MVC2 FormCollection against Model

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.")]
    [Stri开发者_如何转开发ngLength(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!


What about having the small form use the NameAndEmail class and the large form use SsUserMetaData?

class NameAndEmail
{
    [Required(ErrorMessage = "Name is a required field.")]
    [StringLength(100, ErrorMessage = "Name must be 100 characters or less.")]
    public string Name { 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; }
}
class SsUserMetaData : NameAndEmail
{
    [Required(ErrorMessage = "Username is a required field.")]
    [StringLength(50, ErrorMessage = "Username must be 50 characters or less.")]
    public string Username { 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; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜