How to use the jQuery validate plugin with strongly typed enumerations?

ⅰ亾dé卋堺 提交于 2019-12-13 07:32:31

问题


I am using a strongly typed view that lists an enumeration of objects, something like this:

@model IEnumerable<Foo>

<table>
    <tbody>
        @Html.EditorForModel()
    </tbody>
</table>

Let's say Foo has a simple numeric property that I want to validate on the client side:

public class Foo
{
    [Required]
    public int Bar { get; set; }
}

Now the editor template for this object looks like this:

@model Foo

<tr>
    <td>@Html.TextBoxFor(m => m.Bar)</td>
</tr>

This works fine, except that the default model binder generates names like [0].Bar. However, [ and ] are invalid characters for the jQuery validate plugin and thus I am always receiving the following error whenever it tries to validate my input:

Syntax error, unrecognized expression: label[for='[0].Bar'], label[for='[0].Bar'] *, #[0].Bar

Is there any way to get the plugin to work while keeping my view bound to the model?

Update: I am using jQuery Validate and Microsoft's Unobstrusive Validation library (yep, the default ASP.NET MVC setup), so I am not directly writing any validation code at all, just if it's of interest!


回答1:


The [ and ] characters aren't strictly invalid for jQuery validate plugin. It's just a sloppy coding which doesn't account for possibility to have those chars in name/id.

There is even a GitHub issue Handling ASP.NET MVC Input Arrays Exception for this.

What I did is I took the code from issue (it has a small problem on it's own) and added this hack on my JavaScript initialization code:

$.validator.prototype.idOrName = function(element) {
    return this.groups[element.name]
        || (this.checkable(element)
            ? element.name
            : element.id || element.name)
        .replace("[", "\\[")
        .replace("]", "\\]");
}

That might not be pretiest or best solution but it works for me. At least till it's fixed in jQuery.

No need to use this, as it's working with 1.13.1 (see issue above for discussion). Be warned, though I haven't checked myself, but ASP.NET MVC still could come bundled with 1.13.0



来源:https://stackoverflow.com/questions/25385833/how-to-use-the-jquery-validate-plugin-with-strongly-typed-enumerations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!