0

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?

Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
Harsh Sharma
  • 910
  • 1
  • 7
  • 20
  • Possible duplicate: http://stackoverflow.com/q/29421572/861716 – Gert Arnold Apr 13 '15 at 08:45
  • Yes, it is almost similar to what you linked, but how can I achive this. Should I validate it implicitly in my business layer or is there any default functionality to do this. – Harsh Sharma Apr 13 '15 at 09:01

1 Answers1

2

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.
Nikolay Kostov
  • 16,433
  • 23
  • 85
  • 123
Marcin J
  • 378
  • 4
  • 15