开发者

Javascript validate X number of fields in an HTML form

I have a form, that has about 10 text entries (user, address, email etc;) and about 50+ entries that are quantity entries (开发者_如何学Cusers 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.

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

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="text" name="b1" class="check" />

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
    });
});

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜