0

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!

4 Answers 4

1

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Just a doubt RobB, will != work? Even if we are talking about id's of elements, they are strings right?
attr('id') returns a string value, which is why you are able to do this comparison of string != string.
1

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

Comments

0

I suggest you use a jquery plugin

eg. http://docs.jquery.com/Plugins/Validation#demo

http://bassistance.de/2011/05/14/release-validation-plugin-1-8-1/

it will make your work easy.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.