Sid
Sid

Reputation: 55

Unique properties from model with ASP.NET Identity

I'm developing a WEB API asp.net project with visual studio 2013, and I'm implementing my custom Identity model for custom registration. For example I've added an email field in the RegisterBindingModel.

This is what I've done: How to extend asp.net web api 2 user?

I've added email property, and I need that property to be unique (as UserName) , but by default that email property can be repeated. My question is how do I make this email property unique, like UserName? I've read that unique properties can be set with UserValidator, but can't find how. Can you tell me how I can make that, with UserValidator or the best way?

And how's the UserName property defined as unique? I can't find it anywhere.

Thank you.

Upvotes: 2

Views: 2307

Answers (1)

Marco
Marco

Reputation: 23937

There a different ways to implement this, but not out of the box. However, you can implement an extensible validation using Fluent Validation

[Validator(typeof(ApplicationUserValidator))]
class ApplicationUser : IdentityUser
{
    public string Email { get; set; }
    //...Model implementation omitted
}

public class ApplicationUserValidator : AbstractValidator<ApplicationUser>
{
    public ApplicationUserValidator()
    {

        RuleFor(x => x.Email).Must(IsUniqueEmail).WithMessage("Email already exists");
    }
    private bool IsUniqueEmail(string mail)
    {
        var _db = new DataContext();
        if (_db.NewModel.SingleOrDefault(x => x.Email == mail) == null) return true;
        return false;
    }
    //implementing additional validation for other properties:
    private bool IsUniqueTelephoneNumber(string number)
    {
      //...implement here
    }
}

Upvotes: 3

Related Questions