Reputation: 5612
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
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
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
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
Reputation:
Try this:
if (nextPgeNum == 3 && $('#txt-centre').val().length < 7 && !$('#txt-centre').val().startsWith("212")) {
That is basic JavaScript.
Upvotes: 1