2

I have an array of characters like :

var invalid_chars = ['<', '>', '$', '@', '&', '+', '(', ')', '[', ']', '{', '}',' ','`'];

and have a string like :

var id_val = $("#id_number").val(); //text field contains "mu 1$2@345"

So I want to restrict the invalid_chars to be entered in the filed.

For that I have the following code:

var id_val = $("#id_number").val();
var invalid_chars = ['<', '>', '$', '@', '&', '+', '(', ')', '[', ']', '{', '}',' ','`'];
if (in_array(invalid_chars,id_val)) {
  console.info("HI");
}

But it shows me error."ReferenceError: in_array is not defined"

Please help me out. Thanks in advance.

5 Answers 5

3

in_array() is a PHP method. In JavaScript use indexOf().

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

Comments

1

It looks like you're using jQuery already, which has an $.inArray() utility method.

Comments

1

You should turn your list of characters into a regular expression, in my opinion:

var badchars = /[<>$@&+()[\]{},` ]/;
if (badchars.test(id_val)) {
  // contains invalid characters
}

Comments

1

You need to write in_array function, simple example:

function in_array( arr, val ) {
    for( var i = 0; i < arr.length; i++) {
        if( arr[ i ] == val ) {
            return true;
        }
    }
}

or using regular expressions:

if( id_val.search( /[^0-9]/g ) == -1 )

or using regex you can strip all non-numeric characters:

var id_val = $("#id_number").val(); //text field contains "mu 1$2@345"
id_val = id_val.replace( /[^0-9]/g, '' );
console.log( id_val ); //text now field contains "12345"

or if you want wo allow latin char's as well:

[^0-9A-Za-z]

^ this will not include space char as well.

Comments

0

You can use indexOf on arrays, but older versions of MSIE's jScript engine don't support this method natively. So either augment the Array.prototype for those browsers (not without risks, obviously), or simply use a string of chars you want to test for:

var nonoChars = '<>$@&+()[]{},`';
for(var i = 0; i< id_val.length; i++)
{
    if (nonoChars.indexOf(id_val.charAt(i)) > -1)
    {
        alert('Char #' + (i + 1) + ' is not allowed!');
        return false;
    }
}
//input ok

But, in this case, a regex simply makes more sense:

if (id_val.match(/[<>$@&+()\[\]{},`]/))
{
    alert('Invalid input');
    return false;
}
//input ok

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.