Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

When validating a JavaScript form, would it be better to process each input field individually, or, where possible check collectively?

e.g.

validate()
{
     noblanks()
     fieldOne()
     fieldTwo()
}

or

validate()
{
     fieldOne()
     fieldTwo()
share|improve this question

1 Answer 1

up vote 3 down vote accepted

I'll suggest a third alternative: Validate the fields in a logical order specific to the form. Sometimes that means validate a form one field at a time. Other times it might be more logical to group fields together and validate by each type of validation or some other criteria.

Lets say you validate each field one at a time. This means that if you find that one field is blank, then you can simply skip all the other validations on that field since they will most likely fail. If you instead checked for all blank field first, then you will need extra logic to make sure that you do not do any other validations on any of the fields that were left blank.

For example, if you require the user to enter their password twice when creating an account, then there's no reason to check if the passwords are the same if the first password field was empty. In this case, both password fields are treated as one logical unit for validation purposes.

Another thing to consider is if a form has both client-side validation and asynchronous server-side validation. Then it makes sense to do all (or most) of the client-side validation first to reduce round-trips to the server.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.