Advertisement
rvnlord

Untitled

Jan 25th, 2020
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.68 KB | None | 0 0
  1. public class RegisterViewModel
  2. {
  3.     [Required]
  4.     [EmailAddress]
  5.     [Remote(action: nameof(AccountController.IsEmailNotInUseAndDomainValid), controller: "Account")]
  6.     [ValidEmailDomain("gmail.com", ErrorMessage = "Email domain must be 'gmail.com'")]
  7.     public string Email { get; set; }
  8.  
  9.     // ...
  10. }
  11.  
  12. public class AccountController : Controller
  13. {
  14.     // ...
  15.  
  16.     [AcceptVerbs("Get", "Post")]
  17.     [AllowAnonymous]
  18.     public async Task<IActionResult> IsEmailNotInUseAndDomainValid(string email)
  19.     {
  20.         var isEmailInUse = await IsEmailNotInUseAsync(email);
  21.         if (isEmailInUse.Value is bool notInUse && notInUse != true || !(isEmailInUse.Value is bool))
  22.             return isEmailInUse;
  23.  
  24.         var isDomainValid = IsDomainValid(email);
  25.         if (isDomainValid.Value is bool valid && valid != true || !(isDomainValid.Value is bool))
  26.             return isDomainValid;
  27.  
  28.         return Json(true);
  29.     }
  30.  
  31.     public async Task<JsonResult> IsEmailNotInUseAsync(string email)
  32.     {
  33.         var user = await _userManager.FindByEmailAsync(email);
  34.         return user == null
  35.             ? Json(true)
  36.             : Json($"Email {email} is already in use.");
  37.     }
  38.  
  39.     public JsonResult IsDomainValid(string email)
  40.     {
  41.         var validEmailDomainAttribute = typeof(RegisterViewModel).GetTypeInfo()?
  42.             .GetProperty(nameof(RegisterViewModel.Email))?.GetCustomAttribute<ValidEmailDomainAttribute>();
  43.         return validEmailDomainAttribute?.IsValid(email) switch
  44.         {
  45.             true => Json(true),
  46.             false => Json(validEmailDomainAttribute.ErrorMessage),
  47.             _ => throw new NullReferenceException()
  48.         };
  49.     }
  50.  
  51.     // ...
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement