使用验证@ Html.validationmessagefor未显示自定义验证消息

时间:2020-10-01 04:02:42

标签: c# asp.net-mvc

我开发了自定义验证属性,该属性验证用户输入的手机号码和电子邮件地址是否已存在于数据库中,如果不存在,它将创建一个新用户,否则将显示一条错误消息,提示“ Mobile”号码或电子邮件已经存在。

以下是自定义验证属性,该属性可以按预期工作(我在调试模式下对其进行了测试)。

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace RBSSTATE.Models
{
    public class VerifyUserExistance:ValidationAttribute
    {
        private ApplicationDbContext _context;
        public VerifyUserExistance()
        {
            _context = new ApplicationDbContext();
        }
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var user =(RegisterViewModel) validationContext.ObjectInstance;
            var foundEmail= _context.Users.FirstOrDefault(x => x.Email.Equals(user.Email));
            var foundPhoneNumber = _context.Users.FirstOrDefault(x => x.PhoneNumber == user.PhoneNumber);
            if (foundEmail != null || foundPhoneNumber != null)
                return new ValidationResult("Email or Phone Number already exists");
            return ValidationResult.Success;
       }
    }
}

这是我的模特

  [Required]
  [VerifyUserExistance]
  [RegularExpression(@"^04([0-9]){8}$", ErrorMessage = "Invalid Mobile Number")]
  public string PhoneNumber { get; set; }
  [Required]
  [VerifyUserExistance]
  [EmailAddress]
  [Display(Name = "Email")]
  public string Email { get; set; }

这是.CSHtml代码,应在其中显示验证消息(它显示除属性[VerifyUserExistance]的验证消息以外的其他验证消息)

 <div class="form-group">
    @Html.LabelFor(x => x.PhoneNumber)
    @Html.TextBoxFor(x => x.PhoneNumber, new { @class = "form-control form-control-lg", placeholder = "Phone Number" })
    @Html.ValidationMessageFor(x => x.PhoneNumber, "", new { @style = "color:red" })
 </div>
 <div class="form-group">
    @Html.LabelFor(x => x.Email)
    @Html.TextBoxFor(x => x.Email, new { @class = "form-control form-control-lg", placeholder = "Email" })
    @Html.ValidationMessageFor(x => x.Email, "", new { @style = "color:red" })
 </div>

请帮助。我尝试了不同的方法,但是没有用。

0 个答案:

没有答案