Is it possible to validate multiple values upon form text entry in JavaScript?-Collection of common programming errors

The short answer is no.

You need to compare every single option with the || operator.

An other option would be to use regexp like that :

function validate() {
    var values = ['this', 'that', 'those'];
    if (document.getElementById('check_value').value.search(new RegExp('^('+values.join('|')+')$')) > -1) {
        $('#block').fadeIn('slow');
    }
    else {
        alert("Nope. Try again");
    }
}

Fiddle : http://jsfiddle.net/78PQ8/1/

You can aswell create your own prototype this type of action:

String.prototype.is = function(){
    var arg = Array.prototype.slice.call(arguments);
    return this.search(new RegExp('^('+arg.join('|')+')$')) > -1;
} 

and call is like that:

function validate() {
    if (document.getElementById('check_value').value.is('this', 'that', 'those')) {
        $('#block').fadeIn('slow');
    }
    else {
        alert("Nope. Try again");
    }
}

Originally posted 2013-11-09 19:41:38.