0

我正在研究 asp.net mvc 3 应用程序视图。我正在根据从数据库中获取的数据动态创建表单。一些文本框是可编辑的,因此在将它们送回保存之前需要验证(当然也会有后端验证)但是由于表单的动态特性,我不知道应该验证哪些文本框 - 这个信息也来自数据库,所以我为我可能需要执行的三种类型的验证创建了三个类,并在这里的用户的帮助下我设法写了这个:

$('#submitDocument').click(function (e) {
            if ($(".checkString16 input[type='text']:first").val().length > 16) {
                alert("16 symbols max");
                e.preventDefault();
            } else if (!mathFunctions.isInt($(".checkULong input[type='text']:first").val())) {
                alert("Integer");
                e.preventDefault();
            } else if (!mathFunctions.isFloat($(".checkFloat input[type='text']:first").val())) {
                alert("Float");
                e.preventDefault();
            }
        });
    });

和我的mathFunctions对象:

mathFunctions = {
            isInt: function (value) {
                return value % 1 == 0;
            },

            isFloat: function (value) {
                return ($.isNumeric(value) && value % 1 != 0);
            }
        };

然而。这里的问题是它只检查某个类中元素的第一次命中(即使我删除了:firstfrom input[type='text']:first。因此,如果我有三个类的文本框,checkFloat如果第一个文本框没有,它总是会发出警报通过检查,但如果第一个文本框有正确的数据而其他文本框不正确,则仍会处理提交,并且没有警报消息,我认为它只检查具有此类名称的第一个元素,然后停止。我试图用这个each()函数做点什么:

else if ($(".checkFloat input[type='text']:first")).each(function(){!mathFunctions.isFloat(val())})) {
                alert("Float!");
            }

但最重要的是 - 它不起作用,而且看起来相当复杂,所以我想我试图以错误的方式使用它。

所以最重要的问题 - 我如何对某个类的所有元素进行检查,即使我认为这可以通过each()其他方式来完成,但我不知道。

4

1 回答 1

1

您在每个循环中使用相同的 val,您必须告诉每个循环采用当前的元素 val,我宁愿不会将其作为 if 条件,尽管它可能。

$('#submitDocument').click(function (e) {
        if ($(".checkString16 input[type='text']:first").val().length > 16) {
            alert("16 symbols max");
            e.preventDefault();
        } else if (!mathFunctions.isInt($(".checkULong input[type='text']:first").val())) {
            alert("Integer");
            e.preventDefault();
        } else {
            var test = false;
            $(".checkFloat input[type='text']").each(function() {
                if (!mathFunctions.isFloat($(this).val())) test = true;
            });

            if (test) {
                alert("Float");
                e.preventDefault();
            }
        }
    });
});
于 2013-05-28T09:52:17.993 回答