views:

191

answers:

0

I want to validate my linq2sql object differently based on its state (new object and updating an existing object.) An example is a User object that hash a Password byte[] field. This stores the hash of the password in the database. However, the user must type in PasswordText and PasswordText2 only if its a new user. I added two extra fields on the partial class for validation.

I am using asp.net MVC and passing the User object through actions using the default model binder.

public partial class User
{
    public string PasswordText { get; set; }
    public string PasswordText2 { get; set; }

    public IEnumerable<RuleViolation> GetRuleViolations() {

        // If this is a new user valid the following properties
        if (string.IsNullOrEmpty(PasswordText)) {
            yield return new RuleViolation("Please enter your password.", "password");
        } else if (string.Equals(PasswordText, PasswordText2)) {
            yield return new RuleViolation("Passwords do not match.", "password");
        }

        yield break;
    }
}