0

I'm trying to validate input using JavaScript, what i want is to bring up an alert if the user enters something that is not included in my array.

Here is what i have so far

var validAr = ["1","2","3","4","5","6","7","8","9","10","m","M"];
//dont mind the i it's been previously declared
val =+ document.getElementById('arrow_' + i + '_1').value

alert(val);
alert(validAr.indexOf(val));

If for example in the above the user enters '5' I'll alert '5', the value of val and then -1 which means that it does not belong to the array. How do I solve this?

1
  • I think you better use regular expression for such kind of validations. here is a useful reference tech.pro/tutorial/1214/… Commented Feb 20, 2014 at 9:20

4 Answers 4

3

Your array contains strings but you're converting the value to a number:

val = +document.getElementById('arrow_'+i+'_1').value
//    ^ Remove this to keep the value as a string

Since Array.prototype.indexOf performs a strict equality comparison it fails to find the value in the array.

You could replace the values of your array with actual numbers, but since "m" and "M" will not convert to numbers it won't work that way (you'll end up with NaN when you try to coerce them).

Sign up to request clarification or add additional context in comments.

1 Comment

Yes now i understand, im converting it to number cause i need it later. Converted to string just for the validation and works fine.
1

just convert your value in string

    alert(validAr.indexOf(val.toString()));

and also remove + from +document.getElementById('arrow_'+i+'_1').value

so your code will be

var validAr = ["1","2","3","4","5","6","7","8","9","10","m","M"];
//dont mind the i it's from a for above
val = document.getElementById('arrow_'+i+'_1').value;

alert(val);
alert(validAr.indexOf(val.toString()));

1 Comment

Yes, i was using the + cause i need the number of it later. That fixed it. Thank you
0

try

   $(document).ready(function () {
        var validAr = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "m", "M"];

        $("#text").change(function () {
            if (jQuery.inArray($(this).val(), validAr) == -1) {
                alert("exception");
            }
        });
    });

<input type="text" id="text" />

1 Comment

why not just go with < 0 ?
0

As you are using jQuery you can do:

if (jQuery.inArray(val,validAr)==-1)
{
    alert('Invalid');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.