0

I'm trying to validate an input field to see if the value entered contains a number or the letters X or Y at the start of the string:

var t_index_array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'Y'];

for(var i=0, l=t_index_array.length; i < l; i++){
   if (document.form.topography_index.value.toUpperCase().substr(0,1) != t_index_array[i]){
    alert ( "The Topography index field needs to start with a number between 0 and 9 or the letters X or Y." );
    valid = false;
    return valid;
   }
}

This isn't working as the value of t_index_array[i] is always 0. Any ideas?

3
  • 3
    Why don't you use regex?
    – unlimit
    Commented Nov 18, 2013 at 5:02
  • Can you give me an example? Commented Nov 18, 2013 at 5:03
  • See answers provided below.
    – unlimit
    Commented Nov 18, 2013 at 5:10

2 Answers 2

3

Your current logic is checking if it starts with every character, not one of the characters (which is of course impossible).

Instead, you mean something like:

var t_index_array = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'X', 'Y'];

if(!t_index_array.some(function(val) {
    return document.form.topography_index.value.toUpperCase().substr(0,1) == val
})) {
    alert("The Topography index field needs to start with a number between 0 and 9 or the letters X or Y.");
    return false;
}
return true;

But I would use a regex, which is even simpler.

if(!/^[0-9xy]/i.test(document.form.topography_index.value)) {
    alert("The Topography index field needs to start with a number between 0 and 9 or the letters X or Y.");
    return false;
}
return true;

EDIT: Explanation of /^[0-9xy]/i.

  • ^ match at beginning of input.

  • [0-9xy] a character 0 through 9, or x, or y

  • i case-insenstive

1
  • Thx the regex looks like the way to go, but I don't understand the i.test bit...should this be if(!/^[0-9xy](document.form.topography_index.value.toUpperCase().substr(0,1)) Commented Nov 18, 2013 at 5:13
1

You could use regex for this case...

var patt1 = /^[\dXY]/i;
var result =inputfield.match(patt1);
//the result will hold the expected output

if result is null..then its not starting with digits or x or y

Thank you @RobG

2
  • He only wants to test the beginning. Commented Nov 18, 2013 at 5:06
  • 1
    I think you mean /^[\dXY]/i and the OP can drop the .toUpperCase() part. And test is more appropriate. And the OP probably wants inputfield.value. And with match, the result won't be empty if no matches are found, it will be null.
    – RobG
    Commented Nov 18, 2013 at 5:12

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