Whether your strings are coming in from
external sources for display, or someone is entering text into a form
field we created, we can access the number for the amount of characters
that the string contains. We can use all of the string comparison
operators in ActionScript 3.0 to compare lengths in our conditional
statements.
The most common thing a webmaster or web applications creator would use
this for is checking the length property of a form field to see if it is
empty or not. Then they give a message back to the user saying "Please
Enter Your Name", if that is the field the person has forgotten to fill
in. We also check many times to see that a username is not too long or
short when a person joins our site through a flash registration form. We
want everything to be just right. And if it is not just right we do not
process a single thing until they get it right.
Note: You can place ( ! )
in front of the variable when using the length property to check if it
is empty.
Here is an example of determining the length of a string and giving a
message when we run a conditional on it. Both examples comparisons below
have identical functionality.
var string1:String = "";
if (!string1.length) {
trace("Please enter some text");
} else {
trace("Your name is " + string1);
}
// ------------------------------------------------
if (string1.length < 1) {
trace("Please enter some text");
} else {
trace("Your name is " + string1);
}
Please enter some text
Now let's make sure that a user has supplied a username between 5 and 15
characters in character length.
var userName:String = "Jack";
if ((userName.length < 5) || (userName.length > 15)) {
trace("Your username must be between 5 and 15 characters");
} else {
trace("Your user name is " + userName);
}
Your username must be between 5 and 15 characters