简体   繁体   English

如何使用jQuery验证插件来验证字符串集合?

[英]How do I use jQuery validation plugin to validation a collection of strings?

I have a Java (Spring MVC) bean that has a collection of strings as a bean property. 我有一个Java(Spring MVC)bean,它具有一个字符串集合作为bean属性。 I can render these in the Freemarker something like this: 我可以在Freemarker中将它们渲染成这样:

[#list listOfStrings as aString]
    <input name="${fieldName}[${aString_index}]" type="text" value="${(currentValue!'')?html}" maxlength="50"/>
[/#list]

That gives me a series of input fields named as "aString[n]", which correctly get passed into the List on the serverside. 这给了我一系列名为“ aString [n]”的输入字段,这些输入字段正确地传递到了服务器端的List中。

This was a single String field and I've recently moved to having a collection. 这是一个String字段,我最近移到了一个集合。 How can I modify my jQuery validation plugin plugin to validate each instance of that field and display validation messages as appropriate for each field? 如何修改我的jQuery验证插件插件以验证该字段的每个实例并显示适合每个字段的验证消息?

Current validation stuff using syntax like this: 当前的验证内容使用如下语法:

$('#myform').validate({
    rules: {
         aString: {
             minlength: 16
         }
    },
    messages: {
         aString: {
             minLength: "failed validation"
         }
    }
});

I need to be able to reference the collection of strings (aString[0], aString[1] .... etc) and render a message so the user knows which of those instances are in error. 我需要能够引用字符串的集合(aString [0],aString [1] ....等)并呈现一条消息,以便用户知道那些实例中有哪些是错误的。

For a min-size validation you don't need to create a new Rule, just mark your fields with minlength='16' and make sure they have ID and NAME, and that they have a label for then: 对于最小大小的验证,您无需创建新规则,只需将您的字段标记为minlength = '16'并确保它们具有ID和NAME,并为其提供了标签:

[#list listOfStrings as aString]
    <label for="${fieldName}_${aString_index}">String: </label>
    <input name="${fieldName}_${aString_index}" name="${fieldName}_${aString_index}" type="text" value="${(currentValue!'')?html}" maxlength="50" minlength="16"/>
[/#list]

And then, you call: 然后,您致电:

$("#myform").validate();

I ended up defining custom methods and applying them using a class. 我最终定义了自定义方法,并使用一个类来应用它们。 This meant I had to add a 这意味着我必须添加一个

<label for="xyz" class="error" />

element in the appropriate place in the HTML. 元素在HTML中的适当位置。

        $.validator.addMethod("codeRequired", $.validator.methods.required,"Please enter a code");
    $.validator.addMethod("codeMinLength", $.validator.methods.minlength, $.format("The code appears to be too short, Please enter a valid {0} digit code."));
    $.validator.addClassRules("code", { codeRequired: true, codeMinLength: 16 });

I then add a class="code" to my input fields I want validating. 然后,在要验证的输入字段中添加class =“ code”。

This appears to work, I'll update later if I find issues with this solution. 这似乎可行,如果我发现此解决方案有问题,请稍后再更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM