0

i want to get the character typed into an html text input field on keypress then validate the character entered against a list of characters and return false if it isn't found in that list

(i don't want to use regular expressions)

by 'list' i mean this:

var acceptable = 'abcd12';

this would prevent, for example, the character 'e' being entered, and so on

the html would look like this:

<input id='someId' type='text' onkeypress='return check(this,event);'>

and the javascript:

function check(element,e) {
    var acceptable = 'abcd12';
    // now get what character was entered
    // if it's in the list, return true
    // if it's not in the list, return false
}

6 Answers6

3

Generally, you would want to bind an onChange event handler to the input field like this:

jQuery('#someId').change(function() {
    var acceptable = ['1', '2', 'a', 'b', 'y'];

    var text = jQuery(this).val();
    var allowed = true;

    // Loop through each character in the string
    var length = text.length;
    for (var i = 0; i < length; i++) {
        // This if condition is fulfilled if the character
        // is not in the array of acceptable characters
        if (jQuery.inArray(text[i], acceptable) != -1)
            allowed = false;
    }

    if (allowed)
        // The input is valid
    else
        // The input contains an unallowed character
});

IMPORTANT:
You always have to do server side verification of the data submitted via a form. Anyone can mess with the code in your script and the HTML code. There are many ways to send false data to your server, no matter what you do to prevent it. Therefore it is extremely important to always do server side verification, since the server environment is entirely in your control.

Side note
The onChange event handler only fires when the field loses focus. If this behaviour is undesirable for you, use this:

jQuery('#someId').on('change keypress paste focus textInput input',function(){
    // The same code as above can be used here
}

See this link for more information on this.

Community
  • 1
  • 1
Thijs Riezebeek
  • 1,762
  • 1
  • 15
  • 22
2

If you create a variable chr with the character that was entered, then

acceptable.indexOf(chr) !== -1

will be true if the character is acceptable (in the string).

1

I'll propose a solution without regexes, although I don't understand that constraint.

Here is a logical proposal to validate your strings.

Take your input string, replace occurrences of each of the valid characters in it with '' (empty string), then just verify that the length is 0. If there are characters left (length > 0), validation doesn't pass.

Also note there are other ways of doing this. Modern browsers support the pattern attribute on text inputs, which will validate against a regex (which is trivial to write for this case).

Jon Surrell
  • 9,444
  • 8
  • 48
  • 54
1

I've made a small jQuery-based solution:

$(document).ready(function() {
  $('#input').keypress(function(e) {
    var allowed = '02468abc';
    var e = e||window.event;
    var k = e.keyCode||e.which;
    var r = allowed.indexOf(String.fromCharCode(k))!=-1;
    r = (k==8||(k>=35&&k<=40)||k==46)?true:r;

    if(!r) {
      e.returnValue = false;
      if(e.preventDefault)
        e.preventDefault();
    }
  });
});

Add the characters you want to pass inside the variable allowed, in this code, allowed characters are 0, 2, 4, 6, 8, a, b, and c.

Just make sure you have this in your HTML:

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

You should be good to go using this.

If jQuery is not an option, leave a comment and I'll add some jQuery-less code.

Edit: Changed code to allow use of arrow keys, backspace, home, end, and delete.

nxasdf
  • 1,088
  • 1
  • 11
  • 11
  • Even though the question asks for a keypress implementation, the goal is much achieved much better by using an onChange event. I believe your code will also block all key presses like backspace, enter, any combination with CTRL etc... – Thijs Riezebeek Feb 07 '15 at 00:40
  • Good catch. I updated the code to allow navigational keys. I notice this doesn't work when pasting into the field, maybe another function to handle that (and other non-typing events like dragging text into the field). The `keypress` listener makes more sense to use for regular typing since it's more noble with event data. `onchange` won't trigger until you focus away from the text field. – nxasdf Feb 07 '15 at 00:54
  • I actually didn't know that, good catch there again ;) However, this will most likely not cause any real issues, since the focus has to be taken off the element to submit the form. – Thijs Riezebeek Feb 07 '15 at 00:56
  • Perhaps, but I think it would be better to disallow characters immediately before focusing away; the user might be typing lots of different things, then focus out, only to realise everything they typed in got stripped out all of a sudden when it was there a second ago. I know this would displease me if I was victim to this :P – nxasdf Feb 07 '15 at 01:16
  • I edited my answer to include a solution for this type of behaviour as well. – Thijs Riezebeek Feb 07 '15 at 15:30
1

Here is a demo of this in action.

HTML

<input type="text">

JavaScript

input = document.querySelector("input");
restrictChars(input, "abc");

function restrictChars(input, chars) {
    input.addEventListener("keypress", function (e) {
        e.preventDefault();
        var character = String.fromCharCode(e.keyCode);
        var isValid = chars.indexOf(character) != -1;
        if (isValid) {
            input.value += character;
        }
    });
}

Basically we prevent the default behaviour of the keypress event (to prevent typing) and use it to obtain the pressed key from the event.keyCode. Then, we test to see if that character is present in the chars parameter (without the use of unnecessary regex in my opinion), if it is, we simulate the normal behaviour by adding the character to the <input>'s value, if it's not, we do absolutely nothing, resulting in nothing getting typed.

Hope this helps!

undefined
  • 3,949
  • 4
  • 26
  • 38
1

Rou's code is clean, but keycode will always return capital letters. If you need this to be case-sensitive, keycode won't work.

I'm also assuming you always want to check the last character entered.

function check(e,element) {
    var acceptable = 'abcd12';
    var char = element.value.charAt(element.value.length - 1);
    if(acceptable.indexOf(char)>=0){
        document.getElementById("result").innerHTML="true";
    }
    else
    {
        document.getElementById("result").innerHTML="false";
    }
}

var inputElement = document.getElementById('someId');
inputElement.addEventListener('keyup', function( e ) {
                check( e, inputElement )
});

Here's the code in JSFiddle if you want to modify it: http://jsfiddle.net/hckytaez/4/

Alex Glover
  • 759
  • 5
  • 15