2013-12-12 84 views
1

我想在ASP.NET MVC4中使用JQuery验证。我的意图是当页面出现任何错误时,应该在控件之前显示。但是错误始终显示在控件的下一行(行)上。JQuery验证错误放置

这里是我的JS,cshtml文件的片段。

$(function() { 
$('#Transaction1Screen1').validate({ 
    errorElement: "div", 
    errorLabelContainer: '#errorMessages', 
    errorPlacement: function (error, element) { 
     error.insertBefore(element); 
    } 
}); 

$("#TextBox1").rules("add", { email: true, messages: { email: 'Verify the e-mail in TextBox1' } }); 

}); 

束映射

@Scripts.Render("~/bundles/jqueryval") 
@Scripts.Render("~/bundles/Common") 
@Styles.Render("~/bundles/themesCss") 
@Scripts.Render("~/bundles/jqueryUI") 
@Scripts.Render("~/bundles/otherControls") 
@Scripts.Render("~/bundles/ClientResources") 
@Scripts.Render("~/bundles/Transaction1Screen1") 

HTML内容

@Html.TextBoxFor(m => m.TextBox1, new Dictionary<string, object> { { "id", "TextBox1" }, { "name", "TextBox1" }, { "Class", "txtfield controlWidth" }, { "jsValidation", "checkEMailAddr" } }) 
<br /> 
@Html.ValidationMessageFor(m => m.TextBox1) 
+0

不是MVC自动创建调用'.validate()'方法的代码吗?此方法不能被调用两次,因为所有后续调用都被忽略。看看***呈现的***页面代码来验证。 – Sparky

回答

0

尝试HTML内容

@Html.ValidationMessageFor(m => m.TextBox1) 
@Html.TextBoxFor(m => m.TextBox1, new Dictionary<string, object> { { "id", "TextBox1" }, { "name", "TextBox1" }, { "Class", "txtfield controlWidth" }, { "jsValidation", "checkEMailAddr" } }) 
+0

这工作。但是我的意图是通过脚本来定义行为。我可以控制脚本而不是HTML。所以,无论在哪里,HTML.Validation对象都可以显示,我想显示脚本中定义的错误消息。 –

0

尝试这样初始化验证:

$(function(){ 
    $("#Transaction1Screen1").validate({ 
    errorElement: "span", 
    errorPlacement: function (error, element) { 
      error.insertBefore(element); 
    } 
    }); 
}); 

errorElement属性意味着你用什么元素来包装你的消息。

如果您使用“div”作为错误元素,元素将被置于新行。

enter image description here

希望这是有帮助的。

+0

似乎没有errorElement更改的影响。无论我使用什么,错误显示在@ Html.ValidationMessageFor(m => m.TextBox1) –