Validation Approaches in ddd

I have a question about validation approaches in ddd. I read pretty controversial opinions about this. Some say that it must live outside the essence, others say that it should be placed into the essence. I am trying to find an approach that I could follow.

As an example, suppose I have a User object with an email address and password. The user has a Register method (email, password). Where should the mail and password verification be located? My personal opinion is that it should be inside the Register () method. But this approach can lead to a messy use of the User class with validation elements. One approach may be to extract the email and password rules in individual policy objects and call them from the Register () method.

How do you rate verification approaches in DDD?

+5
source share
4 answers

-, , - , - , . , , . , . , Reigster. , , . , . , , .

, , , . , -. , JavaScript, . , . , . DRY, . , , .

, , , . , . , , . , .

, , , . , , . .

+5

. ( ), . ? . , , , .

, (, Mail), (, null). . , :

Mail mail = new Mail(blahblahblah); // validates if blah is valid email
User user = new User(name, mail); // validates if name is valid and mail not null
// check if there already exist user with such name or email
repository.Add(user);

, Register (, MembershipService), .

+3

, User . Register (email, password). ?

DDD, , . EmailAddress, Username.

:

class EmailAddress
{
    Constructor(string email)
    {
        if (email.DoesNotMatchRegex("\w+@\w+.\w{2,3}"))
            throw error "email address is not valid"
    }
}

class Username
{
    Constructor(string username)
    {
        if (username.length < 6)
            throw error "username must be at least 6 characters in length"
    }
}

class User
{
    Register(Username username, EmailAddress email)
    {
        if (username == null)
            throw error "user must have a username"

        if (email == null)
            throw new error "user must provide email address"

        // At this point, we know for sure that the username and email address are valid...
    }
}
+2

, : -, . , , , , , , . , , , , , SignUp, - : if (isValid()) register(username, password).

0

All Articles