通过重写CSS实现使用tooltip显示jquery.validate.unobtrusive验证信息,效果如图:
1. 在ViewModel中定义验证规则
[Display(Name = "纬度")]
[Required(ErrorMessage = "{0}不能为空")]
[RegularExpression(@"^\-?\d+(\.\d+)?$", ErrorMessage = "{0}格式不正确,请输入数值")]
[Range(-90, 90, ErrorMessage = "{0}应在{1}到{2}之间")]
public decimal Latitude { get; set; }
2. 在页面中添加ValidationMessage
<div class="form-group">
@Html.LabelFor(x => x.Latitude, new { @class = "col-sm-2 control-label" })
<div class="col-sm-10">
@Html.TextBoxFor(x => x.Latitude, new { @class = "form-control" })
@Html.ValidationMessageFor(x => x.Latitude)
</div>
</div>
3. 预览页面,查看生成的HTML
有错误信息时,html为
4. 重写CSS
这里 .field-validation-error 的父级为bootstrap的.col-sm-10,已有“posttion: relative;”的样式
.field-validation-valid > span,
.field-validation-error > span {
position: absolute;
bottom: -25px;
padding: 3px 12px;
background: #f03040;
color: white;
font-size: 12px;
box-shadow: #999 3px 3px 3px;
z-index: 1;
} .field-validation-valid > span:before,
.field-validation-error > span:before {
content: "";
position: absolute;
z-index: 1;
top: -5px;
left: 12px;
border-top: 0;
border-right: 5px solid transparent;
border-bottom: 5px solid #f03040;
border-left: 5px solid transparent;
}