添加jQuery的验证规则,以动态地创建ASP元素 [英] Adding jQuery validator rules to dynamically created elements in ASP

查看:157
本文介绍了添加jQuery的验证规则,以动态地创建ASP元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有在MVC3项目页面上的一些动态插入表单域。通常我们会加入jQuery验证服务器端,但在这种情况下,我们不能(在UI多个字段生成一个隐藏字段的值 - 而这正是提交我们无法验证对一个隐藏字段,因此,我们必须改为只添加UI验证为字段,用户可以看到)

I've got some dynamically inserted form fields on a page in an MVC3 project. Normally we would add the jQuery validation server-side, but in this case we can't (multiple fields in the UI generate the value for one hidden field - and this is what is submitted. We can't validate against a hidden field, so we must instead add UI-only validation for the fields the user can see)

一旦字段动态添加到网页上,我运行下面的code在容器:

Once the fields are dynamically added to the page, I run the following code over the container:

$container.find(".date").rules("add", {
    required: true,
    messages: {
        required: "The date is required"
    }
});

不过,这是行不通的!奇怪的是,禁止上述code,创建动态元素,然后运行在浏览器JS控制台作品code,但只有默认的验证消息显示。

But it doesn't work! Oddly enough, disabling the above code, creating the dynamic elements, then running the code in the browser JS console works, but only the default validation message shows.

我不知所措。任何想法?

I'm at a loss. Any ideas?

我使用jQuery验证1.9.0&安培;不显眼的插件

I am using jQuery Validation 1.9.0 & the unobtrusive plugin

推荐答案

现在我才明白这是怎么回事用的东西(我理解是关系到ASP.NET以某种方式)不显眼的插件的一面,这里就是你需要做什么

Now that I understand what's going on with the Unobtrusive plugin side of things (which I understand is related to ASP.NET somehow), here's what you need to do:

在您添加新的元素,称之为 $。validator.unobtrusive.parseElement(为newElement),它会被添加到窗体。当你的回答表明,你需要设置新的表单元素中的数据-VAL和数据VAL-需要的属性。

After you add your new element, call $.validator.unobtrusive.parseElement(newElement) and it will get added to the form. As your answer suggested, you need to set the data-val and data-val-required attributes in the new form element.

所以,你最终这个:

//create new form element
$('form fieldset').append('<br>New Field: '+
     '<input type="text" data-val="true" data-val-required="A date is required." name="newField">'+
     ' * Also required');

//add new rules to it
$.validator.unobtrusive
  .parseElement($('form').find('input[name="newField"]').get(0));

如下所示: http://jsfiddle.net/ryleyb/LNjtd/2/

这篇关于添加jQuery的验证规则,以动态地创建ASP元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆