简体   繁体   中英

Validate an input field of a form in Jquery

i have this function in jquery that verify if ALL the fields have at least one character inputed, i mean, if they are not empty, as you can see in the code below:

function validateStep(step){
    if(step == fieldsetCount) return;

    var error = 1;
    var hasError = false;
    $('#formElem').children(':nth-child('+ parseInt(step) +')').find(':input:not(button)').each(function(){
        var $this       = $(this);
        var valueLength = jQuery.trim($this.val()).length;

        if(valueLength == ''){
            hasError = true;
        }

    });
    var $link = $('#navigation_form li:nth-child(' + parseInt(step) + ') a');
    $link.parent().find('.error,.checked').remove();

    var valclass = 'checked';
    if(hasError){
        error = -1;
        valclass = 'error';
    }
    $('<span class="'+valclass+'"></span>').insertAfter($link);

    return error;
}

it happens that in such a big form i have, there is one field that is not required. I still have some difficult in implementing jquery code and i don't see what if i can insert in the middle of this function to say that specific field is not required.

Can anyone give me a little help?

Thanks in advance!

Try checking to see if the ID of the current element doesn't match the ID of the element you wish to exclude:

var $this = $(this); 
if($this.attr('id') != 'SOMEID'){
  // Validate
}

you could tag your required fields with a specific class and iterate trough the fields which have this class 'required', this makes it easy to change your decision which fields you want to check

i suggest the jQuery validation plugin from http://bassistance.de/jquery-plugins/jquery-plugin-validation/ by Jörn Zaefferer, it uses this technique to validate forms

Why not just add an attribute - isRequired=true || isRequired=false and then gather up and validate the elements you need by the attribute value?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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