【问题标题】:Multiple remote validations ASP.NET MVC多个远程验证 ASP.NET MVC
【发布时间】:2020-07-23 02:32:20
【问题描述】:
namespace EmployeeManagement.ViewModels 
{
    public class RegisterViewModel
    {
        [Required]
        [EmailAddress]
        [Remote(action:"IsEmailInUse" , controller:"Account")]
        [ValidEmailDomain(allowedDomain:"mail.com" , ErrorMessage ="Domain should be mail.com")]
        public string Email { get; set; }

        [Required]
        [DataType(DataType.Password)]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name ="Confirm password")]
        [Compare("Password",
            ErrorMessage ="Password and confirmation password do not match")]
        public string ConfirmPassword { get; set; }
    }
}

我正在对 Email 属性应用 ValidEmailDomain 和 IsEmailInUse 验证。我想将这两个验证都视为远程验证。我该怎么做? 如果无法进行远程验证,我该如何将这两个验证放在一起

这是 ValidEmailDomain 的自定义验证代码

public class ValidateEmailDomainAttribute : ValidationAttribute
{
    private readonly string allowedDomain;

    public ValidEmailDomainAttribute(string allowedDomain )
    {
        this.allowedDomain = allowedDomain;
    }
    public override bool IsValid(object value)
    {
        string[] strings = value.ToString().Split('@');
        return strings[1].ToUpper() == allowedDomain.ToUpper();
    } Vali
} 

这是 IsEmailInUse 的远程验证代码

[AcceptVerbs("Get","Post")]
    [AllowAnonymous]
    public async Task<IActionResult> IsEmailInUse(string email)
    {
         var user = await userManager.FindByEmailAsync(email);

        if(user == null)
        {
            return Json(true);
        }
        else
        {
            return Json($"Email {email} already in use");
        }
    }

【问题讨论】:

    标签: asp.net-mvc validation asp.net-core


    【解决方案1】:

    我想将这两个验证都作为远程验证。

    如果Email已经在使用,它必须有有效的域。只需将验证添加到远程方法:

    [AcceptVerbs("Get", "Post")]
    [AllowAnonymous]
    public async Task<IActionResult> IsEmailInUse(string email)
    {
        var user = await userManager.FindByEmailAsync(email);
    
        string[] strings = email.ToString().Split('@');
        var flag = strings[1].ToUpper() == "mail.com".ToUpper();
    
        if (user == null && flag==true)
        {
            return Json(true);
        }
        if(user!=null)
        {
            return Json($"Email {email} already in use");
        }
        else
        {
            return Json($"Email {email} domain is invalid");
        }
    }
    

    查看:

    @model RegisterViewModel
        <form>
            <input asp-for="Email" />
            <span asp-validation-for="Email" class="text-danger"></span>
            @*more properties*@
        </form>
    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-30
      • 2011-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多