views:

28

answers:

1

Hi,

I am using jQuery to create a client-side validation function for a .NET form. Each form element has an id and several of the form elements are required fields.

In my validation script, I thought of creating an array of the id's of the 'not required' elements, then on every 'blur' event checking whether or not the current element ($(this)) is part of the array of elements not to check, but it doesn't seem to be checking against the list.

function validate(){

  $('.form_wrapper input').blur(function(){
    var isEmpty = $(this).val();
    var isRequired = $(this).attr('id');
    var notRequired = ['txtHomePhone','txtWorkPhone','txtMobile','txtStreetAddress','txtSuburb'];

  if (isEmpty == "" && isRequired == notRequired){
        // run conditional validation stuff
        }
        else {
        // run other conditional validation stuff       
        }

    });

}

The area I think I need help with is the if statement checking whether or not the current form element is part of the array of id's not to validate. I am also not really sure if it's actually an array I want/need to use in this situation?

Any help would be great,

Thanks, Tim

+1  A: 

not exactly sure here, but wouldn't you want to be doing

$.inArray(isRequired,notRequired) >= 0

instead of

isRequired == notRequired

EDIT

$.inArray() returns -1 if no match is found. Modified code to correctly show this behavior.

Richard Neil Ilagan
additionally, I'm a jQuery lover and all, but since you mentioned that you're creating this for a .NET form, you might want to look into .NET's native validator controls and see if any of those meet your requirements as well.
Richard Neil Ilagan
WSkid
@WSkid ~ cool! I missed that one. :) Thanks.
Richard Neil Ilagan
mackaytim