View Full Version : Superfluous Code?

02-12-2013, 10:56 PM
I am looking at a script that has this code:

if ( form.yourName.value.length == 0 ) {
alert( "Please provide your name." );
return false;

Then, later on, it has this code:

var findSpace = /^(.+) (.+)$/;
var matchFlag = form.yourName.value.match( findSpace );
if ( matchFlag == null ) {
alert( "Please provide both a first and last name, and resubmit." );
return false;

My impression is that the first test is superfluous because the second test automatically encompasses the first. I would appreciate someone telling me whether I am missing something.

Thanks, as always.


02-13-2013, 02:13 AM
Yeah, though I would drop the second test rather than the first.

Reason being:

It's unreliable. There's nothing to guarantee that "something" + whitespace + "something" is "firstname lastname". It could be "# :)".

It's inefficient. Why would you care about first and last names unless you're going to store them as such? Therefore, you're going to have to separate the first and last when you process the form. What if the user gets confused and enters "Smith, John"? What if the user enters three words? If you need first + last, it's a better approach to ask for them in separate inputs.

One might argue that, since the user can read the form label that says "Your Name" (or whatever), it's reasonable to assume that they do indeed write their name in the text box. But, by that logic, why validate it at all? (I'm being completely serious.) Don't you trust that the user knows what their own name is? Just make sure they didn't forget to fill it in.

On the other hand, the obvious reason to have two different tests is to be able to provide more specific error messages, which is a Good Thing.
But that can be handled more reliably by using separate inputs.