Validating Chromosome Entered is Correct

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;


  1. jeff

    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

  2. manuelcorpas

    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:


Leave a Reply