Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class RegisterViewModel
- {
- [Required]
- [EmailAddress]
- [Remote(action: nameof(AccountController.IsEmailNotInUseAndDomainValid), controller: "Account")]
- [ValidEmailDomain("gmail.com", ErrorMessage = "Email domain must be 'gmail.com'")]
- public string Email { get; set; }
- // ...
- }
- public class AccountController : Controller
- {
- // ...
- [AcceptVerbs("Get", "Post")]
- [AllowAnonymous]
- public async Task<IActionResult> IsEmailNotInUseAndDomainValid(string email)
- {
- var isEmailInUse = await IsEmailNotInUseAsync(email);
- if (isEmailInUse.Value is bool notInUse && notInUse != true || !(isEmailInUse.Value is bool))
- return isEmailInUse;
- var isDomainValid = IsDomainValid(email);
- if (isDomainValid.Value is bool valid && valid != true || !(isDomainValid.Value is bool))
- return isDomainValid;
- return Json(true);
- }
- public async Task<JsonResult> IsEmailNotInUseAsync(string email)
- {
- var user = await _userManager.FindByEmailAsync(email);
- return user == null
- ? Json(true)
- : Json($"Email {email} is already in use.");
- }
- public JsonResult IsDomainValid(string email)
- {
- var validEmailDomainAttribute = typeof(RegisterViewModel).GetTypeInfo()?
- .GetProperty(nameof(RegisterViewModel.Email))?.GetCustomAttribute<ValidEmailDomainAttribute>();
- return validEmailDomainAttribute?.IsValid(email) switch
- {
- true => Json(true),
- false => Json(validEmailDomainAttribute.ErrorMessage),
- _ => throw new NullReferenceException()
- };
- }
- // ...
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement