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 Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

how do i check if a string has a specific character?

Status
Not open for further replies.

lastingforhours

Programmer
Dec 29, 2004
49
US
i have an input text field where the user will type in an email address and submit some data. when they click submit i want it to check to see if that text field contains the @ symbol and if it doesnt, it will stop and let them know that they need to enter a valid email address.

no matter what i do, it always returns false when there is in fact an @ symbol in the string. can someone help me with this? here are the three functions that i tried...

1) Comparing characters
function validateEmail() {
var str:String = email.text;
var size:Number = str.length;
var temp:Boolean;
//
for (i=0; i<size; i++) {
if (str == "@") {
temp = true;
} else {
temp = false;
}
}
return temp;
}

2) Comparing ASCII Codes
function validateEmail() {
var str:String = email.text;
var size:Number = str.length;
var temp:Boolean;
//
for (i=0; i<size; i++) {
if (str.charCodeAt(i) == 64) {
temp = true;
} else {
temp = false;
}
}
return temp;
}

3) Converting string to array
function validateEmail() {
var str:String = email.text;
var size:Number = str.length;
var strArray:Array = str.split("");
var temp:Boolean;
//
for (i=0; i<size; i++) {
if (strArray == "@") {
temp = true;
} else {
temp = false;
}
}
return temp;
}

thanks!!
 
Try:
[tt]//
function validateEmail() {
var str:String = email.text;
var size:Number = str.length;
var temp:Boolean = false;
for (i=0; i<size; i++) {
if (str.charAt(i) == "@") {
temp = true;
return temp;
}
}
return temp;
}
//[/tt]

However, I would do it like this if I were you!
[tt]//
function validateEmail() {
var str:String = email.text;
var temp:Boolean;
str.indexOf("@")<0 ? temp=false : temp=true;
return temp;
}
//[/tt]

Kenneth Kawamoto
 
yes!! thank you so much, i did it the way you suggested and it works now. thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top