nsilva
nsilva

Reputation: 5612

jQuery - check if value starts with specfic characters

I have some validation at the moment that returns false if a user enters a value that is less than 7 characters as so:

        if (nextPgeNum == 3 && $('#txt-centre').val().length < 7 ) {

            alert("Invalid Cost Centre");

            return false;

        }

What I need to do is add further validation to the same element to return false if #txt-centre doesn't begin with '212'

Upvotes: 0

Views: 1842

Answers (4)

David Thomas
David Thomas

Reputation: 253328

I'd suggest, for simplicity, using indexOf():

if (nextPgeNum == 3 && $('#txt-centre').val().length < 7 &&  $('#txt-centre').val().indexOf('212') === 0) {

    alert("Invalid Cost Centre");

    return false;

}

It might be worth caching the value, since it's being accessed twice, and also removing leading/trailing white-space (with $.trim() or String.prototype.trim()):

var value = $.trim($('#txt-centre').val());
if (nextPgeNum == 3 && value.length < 7 &&  value.indexOf('212') === 0) {

    alert("Invalid Cost Centre");

    return false;

}

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

I might go with a regex like

if (nextPgeNum == 3 && !/^212.{4,}/.test($('#txt-centre').val())) {
    alert("Invalid Cost Centre");
    return false;
}

Upvotes: 3

T.J. Crowder
T.J. Crowder

Reputation: 1074555

The most straightforward solution with good browser support is substring:

var val = $('#txt-centre').val();
if (nextPgeNum == 3 && val.length < 7 && val.substring(0, 3) !== "212") {

    alert("Invalid Cost Centre");

    return false;
}

I think you wanted !== there...

Upvotes: 0

user1907906
user1907906

Reputation:

Try this:

if (nextPgeNum == 3 && $('#txt-centre').val().length < 7 && !$('#txt-centre').val().startsWith("212")) {

That is basic JavaScript.

Upvotes: 1

Related Questions