Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate only dirty inputs

My current web project has an administration interface, in which the details of a user can be edited (not really revolutionizing, I admit...). The view uses a strongly typed model of a user, with validation attributes:

public class UserPrototype
{
    [Required]
    [StringLength(50, MinimumLength = 4)]
    public string Username { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 1)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 1]
    public string LastName { get; set; }

    [Required]
    [StringLength(250, MinimumLength = 6]
    public string Password { get; set; }

    /*
      And so on
    */
}

When the user is updated, I would like to only update in the database those fields that have actually changed. The main reason is the password field - the password is of course stored as a hash, so when the user is retieved for editing there is nothing meaningful to display in that field. But the model binder validation requires a valid password.

So, can I still use the same class, but somehow only validate those fields that are submitted as changed (this I can accomplish though javascript)? I would like to avoid duplicating the UserPrototype class just to remove the Required attributes.

like image 393
carlpett Avatar asked May 19 '26 05:05

carlpett


1 Answers

Use inheritance, this way you don't have to duplicate.

public class BaseUserPrototype
{
    [Required]
    [StringLength(50, MinimumLength = 4)]
    public string Username { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 1)]
    public string FirstName { get; set; }

    [Required]
    [StringLength(50, MinimumLength = 1]
    public string LastName { get; set; }

    /*
      And so on
    */
}

public class NewUserPrototype: BaseUserPrototype
{
    [Required]
    [StringLength(250, MinimumLength = 6]
    public string Password { get; set; }

    /*
      And so on
    */
}
public class EditUserPrototype: BaseUserPrototype
{
    [StringLength(250, MinimumLength = 6]
    public string Password { get; set; }
    /*
      And so on
    */
}
like image 122
Ralf de Kleine Avatar answered May 21 '26 21:05

Ralf de Kleine