我正在创建一个注册表单。我有一个国家身份证号码。但我希望用户在确认注册后填写它。那我就不在报名表上写。
表示:
National Identity Number
<div class="editor-field">
@Html.EditorFor(model => model.IdentityNumber)
@Html.ValidationMessageFor(model => model.IdentityNumber)
</div>
这是我的财产:
[IdentityNumber("It is not a valid identity number")]
[Required(ErrorMessage = "You have to enter your national number")]
[DisplayName("National Identity Number:")]
public string IdentityNumber { get; set; }
但这不起作用。我认为原因是属性[IdentityNumber]
和[Required]
。如果我评论他们,
public ActionResult Register(Member model)
{
if (ModelState.IsValid)
{
//.....
ModelState.IsValid
是false
。如果我取消注释它们,它将返回true。那么我必须在哪里改变一些东西以允许它?我的意思是,我希望用户在注册后写下他/她的身份证号码。
在我的数据库中,身份国家号码字段也允许为空。
编辑:这是我的属性代码:
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property,
AllowMultiple = false, Inherited = true)]
public class IdentityNumberAttribute : ValidationAttribute, IClientValidatable
{
private string WrongIdentityNumber;
public IdentityNumberAttribute(string message)
:base("Invalid an identity number")
{
WrongIdentityNumber = message;
}
private string identityNumber;
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value == null)
return new ValidationResult(WrongIdentityNumber);
identityNumber = value.ToString();
if (identityNumber.Length != 11)
return new ValidationResult(WrongIdentityNumber);
int sum = 0;
for (int i = 0; i < identityNumber.Length - 1; i++)
{
sum += Convert.ToInt32(identityNumber[i].ToString());
}
return sum.ToString()[1] == identityNumber[10]
? ValidationResult.Success
: new ValidationResult(WrongIdentityNumber);
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
ModelClientValidationRule validationRule = new ModelClientValidationRule();
validationRule.ValidationType = "identitynumber";
validationRule.ErrorMessage = "Invalid identity number";
validationRule.ValidationParameters.Add("param", "");
return new List<ModelClientValidationRule> { validationRule };
//var rule = new ModelClientValidationRule();
//rule.ErrorMessage = FormatErrorMessage(metadata.GetDisplayName());
//rule.ValidationParameters.Add("identitynumber", identityNumber); //küçük harfle yaz html kuralı
//rule.ValidationType = "identitynumber";
//yield return rule;
}
}
答案 0 :(得分:4)
您可以添加此行
ModelState.Remove("ErrorKey");//you can find the error key by stepping though your code
if (ModelState.IsValid)
{
.....
&#34; ErrorKey&#34;将是&#34; YourModelName.YourPropertyName&#34;。设置一个断点并将鼠标悬停在ModelState
上,您就可以看到所有键。
但应创建一个只包含您需要的属性的视图模型,将数据注释放在那里,并将域模型保留在其中。