0

I need to ckeck if Role is in Roles list collection, if isnt, throw validation result. How can i compare this or how can i solve this other way?

public class UserViewModel:IValidatableObject
{
    [Required]
    public string Username { get; set; }
    public IEnumerable<string> Roles { get; set; }

    [Required]
    public string Rola { get; set; }

    public UserViewModel()
    {
        Repozytorium db = new Repozytorium();
        Roles = db.GetAllRoles();
    }
    public UserViewModel(string userName, string rola)
    {
        Repozytorium db = new Repozytorium();
        Roles = db.GetAllRoles();
        Username = userName;
        Rola = rola;
    }
    public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
    {
        if(Roles != Roles )   //this dont work 
            yield return new ValidationResult("role isnt valid", new string[] { "Rola" });
    }
}
Reinstate Monica Cellio
  • 25,975
  • 6
  • 51
  • 67
Dodsonnn
  • 65
  • 1
  • 11

1 Answers1

1

You are checking if your role collection is not your role collection. Instead check that the Rola is not in the collection. With Linq:

if(Roles.All(x => x != Rola ))
    yield return new ValidationResult("Role isn't valid", new [] {nameof(Rola)}; 

Also I recommend using nameof like in the example so that if you change the name of the property, the error message stays valid.

aksu
  • 1,748
  • 1
  • 11
  • 15