SorryEh
SorryEh

Reputation: 928

validating hyphen in javascript to only have one

So I'm trying to validate my text field in javascript so that it would only have one hyphen.

I managed to make it so they cannot be side by side but that's inefficient since the user can still input the hyphen else where.

What I tried to do is this:

if (surname.indexOf("-") > 1)

{

 err += "You cannot use more than one hyphen (-) for Client Surname";

}

But that did not work. I also tried >=2 still no good.

What would you suggest looking into or trying?

Thanks.

Upvotes: 2

Views: 3894

Answers (5)

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

function tooManyHyphens(str){
  return str.split("-").length < 3;
}

var test1 = "Something-Something";
var test2 = "some-thing-some";
var test3 = "some";

console.log(tooManyHyphens(test1));
console.log(tooManyHyphens(test2));
console.log(tooManyHyphens(test3));

http://jsfiddle.net/p9rHe/1/

Upvotes: 2

user745235
user745235

Reputation:

Nah....here is a simple solution my friend:

var str="My-Name-Is-Jhon";
var count = str.match(/-/g);  
alert(count.length);

It will alert you 3.

Upvotes: 2

flagoworld
flagoworld

Reputation: 3194

You can use the .match() + regex to do this.

if(surname.match(/\-/g).length>1) err+='Too many hyphens!';

Upvotes: 2

Marc B
Marc B

Reputation: 360572

if ((surname.length - surname.replace('-', '').length) >= 2) {
     err += "You cannot use more than one hyphen (-) for Client Surname";
}

Basically, take the length of the original string and compare it against the length of the string with all the hyphens removed. If the difference is 2 or more, there's more than 1 hypen.

Upvotes: 4

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

var hyphens = 0;

for(var i = 0; i<surname.length; i++) {
    if(surname.charAt(i) == "-") hyphens++;
    if(hyphens > 1) {
        err += "You cannot use more than one hyphen (-) for Client Surname";
        break;
    }
}

Upvotes: 1

Related Questions