问题: 如何验证设置为输入的默认值? 我的意思是我想忽略默认值,如果用户没有插入任何不同的值,验证将提醒他没有插入任何东西。 型号:
public class ContactUsViewModel
{
[Required(ErrorMessage = "please enter full name")]
public string FullName { get; set; }
[Required(ErrorMessage = "enter email")]
[Email(ErrorMessage = "enter email")]
public string Email { get; set; }
[Required(ErrorMessage = "enter phonenumber")]
[Mobile(ErrorMessage = "enter phonenumber")]
public string PhoneNumber { get; set; }
[Required(ErrorMessage = "please address the issue")]
public string Issue { get; set; }
public IDictionary<string, object> FullNameProperties
{
get
{
return new Dictionary<string, object>()
{
{"Value", "FullName"}
};
}
}
}
查看:
<div class="ui-contact-us-form">
@using (Html.BeginForm("Contact","Home",FormMethod.Post))
{
<ul>
<li>
<label for="FullName" class="form-ui-icon-name ui-block-inline"></label>
<div class="input-black">
@Html.TextBoxFor(x => x.ContactUsViewModel.FullName, Model.ContactUsViewModel.FullNameProperties)
@Html.ValidationMessageFor(x => x.ContactUsViewModel.FullName)
</div>
</li>
<li>
<label for="PhoneNumber" class="form-ui-icon-phone ui-block-inline"></label>
<div class="input-black">
@Html.TextBoxFor(x => x.ContactUsViewModel.PhoneNumber, Model.ContactUsViewModel.PhoneNumber)
</div>
</li>
<li>
<label for="Email" class="form-ui-icon-email ui-block-inline"></label>
<div class="input-black">
@Html.TextBoxFor(x => x.ContactUsViewModel.Email, Model.ContactUsViewModel.EmailProperties)
<input type="text" value="מייל" name="Email"/>
</div>
</li>
<li>
<label for="Issue" class="form-ui-icon-pen ui-block-inline"></label>
<div class="input-black">
@Html.TextBoxFor(x => x.ContactUsViewModel.Issue, Model.ContactUsViewModel.IssueProperties)
</div>
</li>
</ul>
<div class="spacer"></div>
<div class="ui-text-area">
@Html.TextAreaFor(x => x.ContactUsViewModel.Notes)
</div>
<div class="spacer"></div>
<div class="form-ui-btn">
<input type="submit" value="" />
</div>
}
</div>
答案 0 :(得分:0)
对此有多种解决方案。
可能最简单的解决方案是将默认值设置为占位符属性,而不是输入元素的value属性:
@Html.TextBoxFor(x => x.SomeField, new { id = "someFieldId", placeholder = "DefaultVal"})
会产生以下HTML:
<input data-val="true" data-val-required="required" id="someFieldId" name="SomeField" placeholder="DefaultVal" value="">
对模型的正则表达式验证:
[RegularExpression(@"^(?!.*DefaultVal).*$", ErrorMessage = "invalid")]
如果必须在输入元素上使用value属性,则此正则表达式会进行负向查找,以将除文字“ DefaultVal”之外的任何值视为有效。话虽如此,这种灵魂要求您选择一个默认值,该默认值永远不会被期望作为用户的实际输入。
结合[REQUIRED]属性,用户可以输入除“ DefaultVal”之外的任何值,可以为null或为空。