I am trying to tap into the HTML.ValidationMessage() element to write so really custom client side validation with jQuery. Is this even possible? My server side validation is displayed using the HTML.ValidationMessage(), and I am wondering how I would access that element to display a custom message using jQuery before a form submit.
我正在尝试进入HTML.ValidationMessage()元素,以便使用jQuery编写如此自定义的客户端验证。这是可能吗?我的服务器端验证使用HTML.ValidationMessage()显示,我想知道如何在提交表单之前访问该元素,使用jQuery显示自定义消息。
I know there are a few plugins out there to do some of this stuff, but I would really like complete control with my validation.
我知道有一些插件可以做这些事情,但是我真的希望我的验证能够完全控制。
Here is a bit of the Javascript code I have currently. Basically it adds the validation "class" to the input element on submit, however not sure how to access the Html.ValidationMessage to output something like "Email required."
下面是我目前的一些Javascript代码。基本上,它将验证“类”添加到提交的输入元素中,但是不确定如何访问Html。ValidationMessage输出类似“所需邮件”的内容。
<script type="text/javascript">
$(document).ready(function() {
$("input[type=submit]").click(function() {
var valid = true;
// email blank
if ($("input[name='email']").val().length < 1) {
$("input[name='email']").addClass("input-validation-error");
valid = false;
}
return valid;
})
});
</script>
And Code from the View:
以及视图中的代码:
<p>
<label for="email">
Email:</label>
<%= Html.TextBox("email") %>
<%= Html.ValidationMessage("email") %>
</p>
4 个解决方案
#1
8
You could write a ton of code to do this. Or you could just use xVal, which is free and does exactly this, plus much more. Put value annotations on your .NET types, add a couple of simple things to your aspx, and you get jQuery validation for free. Plus it comes with providers for popular frameworks, and it's very customizable in case you need more complex validation.
您可以编写大量的代码来实现这一点。或者你也可以用xVal,它是*的,做的就是这个,再加上更多。在. net类型上添加值注释,在aspx中添加一些简单的东西,就可以免费获得jQuery验证。此外,它还提供了流行框架的提供程序,如果您需要更复杂的验证,它是非常可定制的。
I see no need to reinvent the wheel here.
我认为没有必要在这里重新发明*。
#2
2
Would it be an idea to just use the jquery form validation plugin for client side ? It's easy to implement in the view code. You add a few tags to the input boxes and add a few lines of javascript in the header and you're done. Ofcourse you'd still have to code anything that's 'very custom' so to speak.
在客户端使用jquery表单验证插件会是个好主意吗?在视图代码中很容易实现。在输入框中添加一些标记,在头中添加几行javascript,就完成了。当然,您仍然需要编写任何“非常定制”的代码。
#3
1
If you put the message statically in the page and set it's display to "none", you could show that message at the same time you change the class for the input field.
如果您将消息静态地放在页面中并将其设置为“none”,您可以在更改输入字段的类的同时显示该消息。
<p>
<label for="email">
Email:</label>
<%= Html.TextBox("email") %><span style="display:none" class="email-error">Email required</span>
<%= Html.ValidationMessage("email") %>
</p>
Then in your JS add this line under the part change this:
然后在你的JS中添加这条线的部分改变如下:
if ($("input[name='email']").val().length < 1) {
$("input[name='email']").addClass("input-validation-error");
valid = false;
}
to this:
:
if ($("input[name='email']").val().length < 1) {
$("input[name='email']").addClass("input-validation-error");
$("span.email-error").show();
valid = false;
}
You may need some CSS to position that stuff accordingly, but functionally it should do what you want.
您可能需要一些CSS来相应地定位这些内容,但是在功能上它应该做您想做的。
EDIT:
编辑:
To avoid extra markup replace:
为了避免额外的标记替换:
$("span.email-error").show();
with:
:
$("input[name='email']").after('<span style="display:none" class="email-error">Email required</span>');
#4
0
Create an HtmlHelper that is a ValidatedTextBox. I've done this using reflection on my models, creating a fully dynamic jQuery integration with validation, but a simpler version would work like this (this will probably work but is untested as it stands). A good place to start:
创建一个HtmlHelper,它是一个ValidatedTextBox。我已经在我的模型上使用反射来实现了这一点,创建了一个带有验证的完全动态jQuery集成,但是一个更简单的版本可能会像这样工作(这可能会工作,但目前还没有经过测试)。一个好的开始:
public static MvcForm BeginClientValidatedForm(this HtmlHelper helper, string formId)
{
HttpResponseBase response = helper.ViewContext.HttpContext.Response;
if (helper.ViewData.ModelState.IsValid)
{
response.Write("<ul class=\"validation-summary-errors\"></ul>\n\n");
}
response.Write(ClientValidationHelper.GetFormValidationScript(formId));
response.Write("\n");
// Inject the standard form into the httpResponse.
var builder = new TagBuilder("form");
builder.Attributes["id"] = formId;
builder.Attributes["name"] = formId;
builder.Attributes["action"] = helper.ViewContext.HttpContext.Request.Url.ToString();
builder.Attributes["method"] = HtmlHelper.GetFormMethodString(FormMethod.Post);
response.Write(builder.ToString(TagRenderMode.StartTag));
return new MvcForm(response);
}
And the corresponding "GetFormValidationScript":
和相应的“GetFormValidationScript”:
public static string GetFormValidationScript(string formId)
{
string scriptBlock =
@"<script type=""text/javascript"">
$(document).ready(function() {{
$(""#{0}"").validate({{
meta:""rules"",
onkeyup:false,
onfocusout:false,
onclick:false,
errorClass:""input-validation-error"",
errorElement:""li"",
errorLabelContainer:""ul.validation-summary-errors"",
showErrors: function(errorMap, errorList) {{
$(""ul.validation-summary-errors"").html("""");
this.defaultShowErrors();
}}";
// etc...this is the standard jQuery.validate code.
return string.Format(scriptBlock, formId);
}
public static string ClientValidatedTextbox(this HtmlHelper htmlHelper, string propertyName, IDictionary<string, object> htmlAttributes, string validationType)
{
var cssClassBuilder = new StringBuilder();
cssClassBuilder.Append("text ");
if (htmlAttributes == null)
{
htmlAttributes = new Dictionary<string, object>();
}
else if(htmlAttributes.ContainsKey("class"))
{
cssClassBuilder.Append(htmlAttributes["class"]);
}
switch validationType
{
case "email":
cssClassBuilder.Append(" {rules: {email: true, messages: {email: 'A valid email is required.'}} } ");
break;
}
htmlAttributes["class"] = cssClassBuilder.ToString();
return htmlHelper.TextBox(propertyName, htmlAttributes);
}
#1
8
You could write a ton of code to do this. Or you could just use xVal, which is free and does exactly this, plus much more. Put value annotations on your .NET types, add a couple of simple things to your aspx, and you get jQuery validation for free. Plus it comes with providers for popular frameworks, and it's very customizable in case you need more complex validation.
您可以编写大量的代码来实现这一点。或者你也可以用xVal,它是*的,做的就是这个,再加上更多。在. net类型上添加值注释,在aspx中添加一些简单的东西,就可以免费获得jQuery验证。此外,它还提供了流行框架的提供程序,如果您需要更复杂的验证,它是非常可定制的。
I see no need to reinvent the wheel here.
我认为没有必要在这里重新发明*。
#2
2
Would it be an idea to just use the jquery form validation plugin for client side ? It's easy to implement in the view code. You add a few tags to the input boxes and add a few lines of javascript in the header and you're done. Ofcourse you'd still have to code anything that's 'very custom' so to speak.
在客户端使用jquery表单验证插件会是个好主意吗?在视图代码中很容易实现。在输入框中添加一些标记,在头中添加几行javascript,就完成了。当然,您仍然需要编写任何“非常定制”的代码。
#3
1
If you put the message statically in the page and set it's display to "none", you could show that message at the same time you change the class for the input field.
如果您将消息静态地放在页面中并将其设置为“none”,您可以在更改输入字段的类的同时显示该消息。
<p>
<label for="email">
Email:</label>
<%= Html.TextBox("email") %><span style="display:none" class="email-error">Email required</span>
<%= Html.ValidationMessage("email") %>
</p>
Then in your JS add this line under the part change this:
然后在你的JS中添加这条线的部分改变如下:
if ($("input[name='email']").val().length < 1) {
$("input[name='email']").addClass("input-validation-error");
valid = false;
}
to this:
:
if ($("input[name='email']").val().length < 1) {
$("input[name='email']").addClass("input-validation-error");
$("span.email-error").show();
valid = false;
}
You may need some CSS to position that stuff accordingly, but functionally it should do what you want.
您可能需要一些CSS来相应地定位这些内容,但是在功能上它应该做您想做的。
EDIT:
编辑:
To avoid extra markup replace:
为了避免额外的标记替换:
$("span.email-error").show();
with:
:
$("input[name='email']").after('<span style="display:none" class="email-error">Email required</span>');
#4
0
Create an HtmlHelper that is a ValidatedTextBox. I've done this using reflection on my models, creating a fully dynamic jQuery integration with validation, but a simpler version would work like this (this will probably work but is untested as it stands). A good place to start:
创建一个HtmlHelper,它是一个ValidatedTextBox。我已经在我的模型上使用反射来实现了这一点,创建了一个带有验证的完全动态jQuery集成,但是一个更简单的版本可能会像这样工作(这可能会工作,但目前还没有经过测试)。一个好的开始:
public static MvcForm BeginClientValidatedForm(this HtmlHelper helper, string formId)
{
HttpResponseBase response = helper.ViewContext.HttpContext.Response;
if (helper.ViewData.ModelState.IsValid)
{
response.Write("<ul class=\"validation-summary-errors\"></ul>\n\n");
}
response.Write(ClientValidationHelper.GetFormValidationScript(formId));
response.Write("\n");
// Inject the standard form into the httpResponse.
var builder = new TagBuilder("form");
builder.Attributes["id"] = formId;
builder.Attributes["name"] = formId;
builder.Attributes["action"] = helper.ViewContext.HttpContext.Request.Url.ToString();
builder.Attributes["method"] = HtmlHelper.GetFormMethodString(FormMethod.Post);
response.Write(builder.ToString(TagRenderMode.StartTag));
return new MvcForm(response);
}
And the corresponding "GetFormValidationScript":
和相应的“GetFormValidationScript”:
public static string GetFormValidationScript(string formId)
{
string scriptBlock =
@"<script type=""text/javascript"">
$(document).ready(function() {{
$(""#{0}"").validate({{
meta:""rules"",
onkeyup:false,
onfocusout:false,
onclick:false,
errorClass:""input-validation-error"",
errorElement:""li"",
errorLabelContainer:""ul.validation-summary-errors"",
showErrors: function(errorMap, errorList) {{
$(""ul.validation-summary-errors"").html("""");
this.defaultShowErrors();
}}";
// etc...this is the standard jQuery.validate code.
return string.Format(scriptBlock, formId);
}
public static string ClientValidatedTextbox(this HtmlHelper htmlHelper, string propertyName, IDictionary<string, object> htmlAttributes, string validationType)
{
var cssClassBuilder = new StringBuilder();
cssClassBuilder.Append("text ");
if (htmlAttributes == null)
{
htmlAttributes = new Dictionary<string, object>();
}
else if(htmlAttributes.ContainsKey("class"))
{
cssClassBuilder.Append(htmlAttributes["class"]);
}
switch validationType
{
case "email":
cssClassBuilder.Append(" {rules: {email: true, messages: {email: 'A valid email is required.'}} } ");
break;
}
htmlAttributes["class"] = cssClassBuilder.ToString();
return htmlHelper.TextBox(propertyName, htmlAttributes);
}