I have created an Asp.Net Web Api project and used Individual user accounts. When I am adding users to the table the default system automatically checks if the email address supplied already exists in the table, if so a bad request is thrown otherwise the user can be submitted.
How can I also check if the Phone Number is unique and hasn't already been submitted to the table?
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
**using (ApplicationDbContext db = new ApplicationDbContext())
{
var foundPhoneNumber = await db.Users.FirstOrDefaultAsync(x => x.PhoneNumber.Equals(model.PhoneNumber));
if (foundPhoneNumber != null)
{
return BadRequest("Phone number already exists");
}
}**
var user = new ApplicationUser()
{
UserName = model.Email,
Email = model.Email,
PhoneNumber = model.PhoneNumber,
FirstName = model.FirstName,
LastName = model.LastName,
MemberNumber = model.MemberNumber,
CarReg = model.CarReg
};
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
I have queried the database to check if there is a Phone Number with the same number. This works, but is there a better way to do this?
Modify your ApplicationUser call and add the following attributes.
public class ApplicationUser : IdentityUser
{
[MaxLength(17)]
[IsUnique]
public string PhoneNumber { get; set; }
}
You can override ValidateEntity method in ApplicationUserDbContext class, it will trigger on SaveChanges method.
protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items)
{
if (entityEntry != null && entityEntry.State == EntityState.Added)
{
var errors = new List<DbValidationError>();
////User Validation
if (entityEntry.Entity is ApplicationUser user)
{
if (this.Users.Any(u => string.Equals(u.PhoneNumber, user.PhoneNumber)))
{
errors.Add(new DbValidationError("User",
string.Format($"Phonenumber {user.PhoneNumber} is already taken")));
}
}
if (errors.Any())
{
return new DbEntityValidationResult(entityEntry, errors);
}
}
return new DbEntityValidationResult(entityEntry, new List<DbValidationError>());
}
Validation can be added via a custom ValidationAttribute that you add to the PhoneNumber property on you model. Here is a simple example:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class NotABananaAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var inputValue = value as string;
var isValid = true;
if (!string.IsNullOrEmpty(inputValue))
{
isValid = inputValue.ToUpperInvariant() != "BANANA";
}
return isValid;
}
}
And its used liked this...
public class Model
{
[NotABanana(ErrorMessage = "Bananas are not allowed.")]
public string FavoriteFruit { get; set; }
}
Example sourced from: https://riptutorial.com/csharp/example/18486/creating-a-custom-validation-attribute
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.