jmenezes
jmenezes

Reputation: 1926

Javascript add a regex inside a function for validation

I'm trying to add a regular expression inside a JavaScript function. I've never done something like this before. How is this done? I've got the length part correct, but the regex has me stuck.

if(searchTerm('Ford GT')) {
    alert ('Query OK');
} else {

    alert ('Invalid query');
}


function searchTerm(query) {
    if( (query.length >= 2 && query.length <= 24) && (query.test('/^[a-z0-9()\- ]+$/i')) )  {
        return true;
    } else {
        return false;
    }
}

Upvotes: 0

Views: 58

Answers (3)

user3578445
user3578445

Reputation:

test is method of the RegExp Object (try console.log({}.toString.call(/\d/));), not of the String Object. Thats's why use the syntax regex.test(string). Also your function can be rewritten more compact:

function searchTerm(query) {
    return query.length >= 2 && query.length <= 24 && /^[-a-z\d() ]+$/i.test(query);
}

Upvotes: 0

coffee_addict
coffee_addict

Reputation: 966

function searchTerm(query) {
    var regex = /^[a-z0-9()\- ]{2,24}$/i;
    return regex.test(query);
}

Upvotes: 0

adeneo
adeneo

Reputation: 318202

When using .test() the syntax is regex.test(string)

/^[a-z0-9()\- ]+$/i.test(query)

Upvotes: 1

Related Questions