Harsh Sharma
Harsh Sharma

Reputation: 930

Validate Unique Value in MVC5 and EF6

In my MVC application I have a requirement where I want user to insert Unique value in a column.

i.e.: Username should be unique in Users table.

I used [Indes(IsUnique = true)] data annotation in my model.

But when I insert duplicate value in the field it throws an exception, but I want to display an Error Message on my View saying Please try with a different Username

Please help me what should I do here?

Upvotes: 0

Views: 1493

Answers (1)

Marcin J
Marcin J

Reputation: 378

You can use one of those:

  1. Write your CustomValidator (ny recommendation)

    [CustomRemoteValidator(ErrorMessage = @"Username already in use")]
    public string Username{ get; set; }`
    

    And override IsValid method

    public override bool IsValid(object value)
    {
        return !(this.DbContext.Set<User>().Any(a => 
            a.Username.Equals((string)value));
    }
    
  2. Check it in your business layer.

  3. Check it before save entity in database by overriding SaveChanges() method.

Upvotes: 2

Related Questions