0

I'm creating UserValidator to validate UserViewModel using FluentValidation MVC 5

public class UserValidator : AbstractValidator<UserViewModel>
{
    public UserValidator()
    {
        RuleFor(u => u.UserName)
            .NotEmpty()
            .Length(1, 50);
        RuleFor(u => u.Password)
            .NotEmpty()
            .Length(6, 20);
        // How to validate Role must be selected from dropdownlist?
    }
}

UserViewModel
- UserID - int
- Username - varchar(50)
- Password - varchar(20)
- RoleID - int

How to create RuleFor for RoleID, that user must select the role before submit? If using DataAnnotation, I can simply use [Required] attribute.

Willy
  • 1,689
  • 7
  • 36
  • 79

1 Answers1

1

Check the documentation for Built in Validators.

You can use NotEmpty:

Ensures that the specified property is not null, an empty string or whitespace (or the default value for value types, eg 0 for int)

RuleFor(u => u.RoleID).NotEmpty()

or make the property nullable and use NotNull:

Ensures that the specified property is not null.

RuleFor(u => u.RoleID).NotNull()
Zabavsky
  • 13,340
  • 8
  • 54
  • 79