-1

I have an example code which checks that which user types in the input are available in the javascript array.

var postcodes = ["00-240", "80", "32", "90", "91"];
$('#test').keyup(function () {
    var val = this.value; 
    var m = $.map(postcodes, function (value, index) {
        var reg = new RegExp('^' + val + '.*$');
        return value.match(reg);
    });
    $('#msg').text(m.length && val.length ? 'VALID' : 'INVALID');
});

I want to set VALID also when user type: 80-215, 80-512, 32-125 etc. Now if i type 80 or 32 it's display valid but when I write 80-215 or 32-111 it will show invalid. I want to check that some string from the array is available in string which is request from user (with emphasis on the order of letters).

I will be gratefull for any tips.

Regards

dtx
  • 241
  • 1
  • 11
  • 1
    Your code needs to go in the question. You can't just dump a jsbin/jsfiddle link on us an expect us to debug it for you; your question needs to be self-contained and answerable without opening any external links. – user229044 Aug 07 '14 at 16:49
  • Sorry I corrected my mistake. – dtx Aug 07 '14 at 16:54

1 Answers1

0

You have some problems:

  • You must escape special regex characters when you build a regex from an untrusted string.
  • Since you want to match strings starting with codes in the array, you must build regular expressions from each array entry, not user input
  • To test if there are some matches, better use Array.prototype.some than Array.prototype.map
  • Text fields can change by other ways than keyboard, e.g. pasting with mouse. Better listen to input event instead of keyup one.
var postCodes = ["00-240", "80", "32", "90", "91"],
    postRegExp = postCodes.map(function(code) {
        return new RegExp('^' + code.replace(/[.^$*+?()[{\\|]/g, '\\$&'));
    });
document.getElementById('test').oninput = function () {
    var val = this.value,
        m = postRegExp.some(function(regExp){
            return regExp.test(val);
        });
    document.getElementById('msg').innerHTML = m ? 'VALID' : 'INVALID';
};

However, instead of regex, you could try ES6 String.prototype.startsWith:

var postCodes = ["00-240", "80", "32", "90", "91"];
document.getElementById('test').oninput = function () {
    var val = this.value,
        m = postCodes.some(code => val.startsWith(code));
    document.getElementById('msg').innerHTML = m ? 'VALID' : 'INVALID';
};
Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513