Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

URGENT: match method

Status
Not open for further replies.

alsaffar

Programmer
Oct 25, 2001
165
0
0
KW
Hi there,

I'm lost in the 'match' method :) I read and read and read about it but STILL can not figure how to build the argument of the characters to be compared!

I want the text input box to accept only english characters and numbers and a dash, how can I do it? Following is a part from my script:

CompareArgument = /-|[abcdefghijklmnopqrstuvwxyz]|[1234567890]/;

if (TextInput.value.match(CompareArgument))
alert ('OK');
else
alert ('NOT');

Please help.

If you need the full script please tell me :)

Thanx in advance ;)
 
This certainly isn't he most elegant way of doing it. But im not too good with regular expression matching. I think this will do what you want.

The problem with your code is that it was saying it was ok if ANY part of the string matched. I dont know how to say "only if it all matches" in a pattern so I'm just going through each character and seeing if that matches... if it doesn't set and flag to say its not ok.

Code:
var CompareArgument = /-|[a-z]|[0-9]/;
	var ok = true;

	for(var i = 0; i<TextInput.value.length; i++)
	{
		var myChar = TextInput.value.charAt(i);
		myChar = myChar.toString();
		if (!myChar.match(CompareArgument))
		{
			ok = false;
		}
	}

	if(ok)
	{
		alert("OK!");
	} else {
		alert("NOT OK!");
	}

Hope that at least points you in the right direction.

Westbury

If it aint broke, redesign it!
 
You could try it another way. The way i'd do it is by checking each character in a for loop, try this.

function checkValCorrect()
{
var valCorrect = true;
TextInput = document.formName.fieldName.value;
for (i=0; i<TextInput.length; i++)
{
Char = TextInput.charAt(i);
if (Char.match(/[abcdefghijklmnopqrstuvwxyz1234567890]/))
{
continue;
}
else
{
valCorrect = false
}
}
if (valCorrect == true)
{
alert ('OK');
}
else
{
alert ('NOT');

}
}

hth

Stewart
 
the match() method returns an array of matches to the pattern, or null. if you just want to see if your input matches the pattern, use pattern.test(string)
Code:
CompareArgument = /^[a-z0-9\-]+$/ig;

if (CompareArgument.test(TextInput.value))
  alert ('OK');
else
  alert ('NOT');

=========================================================
-jeff
try { succeed(); } catch(E) { tryAgain(); } finally { rtfm(); }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top