IlludiumPu36
IlludiumPu36

Reputation: 4304

JavaScript find substr in array

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?

Upvotes: 0

Views: 109

Answers (2)

sam
sam

Reputation: 2486

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

Upvotes: 1

Paul Draper
Paul Draper

Reputation: 83421

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

Upvotes: 3

Related Questions