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

问题描述

我开发了自定义验证属性,该属性验证用户输入的手机号码和电子邮件地址是否已存在于数据库中,如果不存在,它将创建一个新用户,否则将显示一条错误消息,提示“ 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,placeholder = "Email" })
    @Html.ValidationMessageFor(x => x.Email,new { @style = "color:red" })
 </div>

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

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)