Validating Chromosome Entered is Correct

September 10th, 2009 § 4 Comments

When you have a web form and one of the fields to be entered is the Chromosome Number, you’d be wise to check that the user does not enter the wrong thing (e.g. ’0′ , ‘X1′, ’21.13′). Thus a validation check may save you some headaches.

I set out to find the appropriate regular expression in Javascript that returns an error when the chromosome entered is not 1-22 or X or Y. It turns out that for me it wasn’t that easy to solve this little problem. I searched in Google to see if anyone had posted the solution to the problem and found nothing meaningful.

Therefore I paste below the solution I wrote. I must admit that it is rather ugly the fact that I have to use two if expressions. I would appreciate if any  reader posted a more elegant solution. But for now, this code seems to work fine.

function notValidChr(field)
{
  // Field may start with a number or optionally two
  if ( field.value.match(/^\d\d?$/)
      // Is it an integer greated than 0?
      && (0 < parseInt(field.value)
            // Is it an integer smaller than 23?
            && parseInt(field.value) <23
          )
      )
  {
    // If all conditions above are met, notValidChr is not true
    return false;
  }
  // Check if it is a valid X or Y chromosome
  if (field.value.match(/^[XY]$/)) {
    // If so notValidChr is not true
    return false;
  }
  // Yes! the text entered is not a valid chromosome
  return true;
}

§ 4 Responses to Validating Chromosome Entered is Correct

  • jeff says:

    Ah my bad I misread the following

    “when the chromosome entered is not 1-22 or X or Y.” to mean it would always include the an X or Y

    Hope it helps anyway

  • manuelcorpas says:

    thanks Jeff,

    your solution does not match numbers like 1, 13, 22. But it matches something like 22x or 3y.

    A modified version of your solution seems to work better:

    ^([1-9]|1[0-9]|2[0-2]|[X|Y])$

  • jeff says:

    Would the following regex help? Haven’t tried it in JS, but should just work….

    ^([1-9]|1[0-9]|2[0-2])(X|Y)$

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

What’s this?

You are currently reading Validating Chromosome Entered is Correct at Manuel Corpas' Blog.

meta

Follow

Get every new post delivered to your Inbox.