Javascript验证HTML表单中的X个字段 [英] Javascript validate X number of fields in an HTML form

查看:73
本文介绍了Javascript验证HTML表单中的X个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,有大约10个文本条目(用户,地址,电子邮件等;)
和大约50个以上数量条目的条目(用户选择此项目的2倍,此项目的5倍)。

I have a form, that has about 10 text entries (user, address, email etc;) and about 50+ entries that are quantity entries (users select 2x of this item, 5x of this item).

现在我从其他人那里继承了这个表格(现在我有责任在客户要求时更新它)。

Now I inherited this form from someone else (now its my duty to keep it up to date, when the customer requests it).

我不想重写所有内容,但我想为数量字段添加验证。

I don't want to re-write it all, but I would like to add validation for the quantity fields.

现在数量字段都被命名为不同的东西(b1,c55,d,12)

Now the quantity fields are all named different things (b1,c55,d,12)

基本上我想写一个脚本(但不知道如何搜索这个,或者完成此操作)JS方面,将忽略我知道的标签(用户,地址,电子邮件等;)但检查其他人是否为数字(空的 - 未选中,或1-99)

Basically I would like to write a script (but don't know how to search for this, or accomplish this) JS side, that would ignore the tags I know (user, address, email etc;) but check if the others are numbers (either empty - not selected, or 1-99)

推荐答案

应用于元素(我的代码使用类检查)像这样:

Apply a class to the elements (my code uses a class check) like so:

< input type =textname =b1class =check/> ;

以及以下jQuery代码,它只会检查检查 class。

and the following jQuery code, which will only check those elements with the check class.

$('#myformid').submit(function(){
    $(':input.check').each(function(){
        field = $(this);
        valInt = parseInt(field.val()); // value as an integer

        if (isNaN(valInt) || (valInt < 1 || valInt > 99)) // displays an error if the val is < 1 or > 99
             alert('Error in the field ' + field.attr('name') + ': must be number from 1-99'); // change this to whatever you want the form to do if there's an error
    });
});

基本上它的作用如下:当提交表单时,它会遍历你的每个字段d喜欢它(表示:input.class 用正确的类捕获每个字段)并检查它是否是(a)一个数字,以及(b)是否小于1或大于99.如果它是一个数字且超出范围,它会警告用户错误。您可以将 alert()通知更改为您希望表单具有的任何错误管理。

Basically what this does is the following: when the form is submitted, it goes through every field you'd like it to (denoted :input.class to catch each field with the correct class) and checks if it's (a) a number, and (b) less than 1 or greater than 99. If it's a number and is outside the range, it alerts the user of an error. You can change the alert() notification to whatever error management you'd like your form to have.

这篇关于Javascript验证HTML表单中的X个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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