Validation of input text - actionscript-3

I have 'myTextarea' so users can put their text into it, and they should use only "numbers" and ",".
Text they input must be like this:
2,4,6,2,67,43,...number, comma, number, comma and so on.
This line of code helps me:
levelTextarea.restrict = "0-9,";
But the problem is that users can type many commas in a row
2,,,,3,44,5,6,5,5....
and I need number,comma, number...
I will convert their input into an array.
Is it possible to validate input text, something like:
if (myTextarea is valid)
{
continue
}
else
{
trace ("invalid input");
}

There may be a better way, but one simple way that comes to mind is just doing this:
var myValue:String = myTextarea.text;
while(myValue.indexOf(",,") >= 0){
myValue = myValue.replace(",,",",");
}
Of course, if you just want an array of numbers at the end of the day, you could just do this instead:
//create the array
var arr:Array = myTextarea.text.split(",");
//loop backwards through the array and remove anything that is empty
for(var i:int=arr.length-1;i>=0;i--){
if(!arr[i] || arr[i] == ""){
arr.splice(i,1);
continue;
}
//convert the value to a number
arr[i] = Number(arr[i]);
}
Now you'd have an array of all the number (separated by commas) from the text input

This is one way to do it:
var a:String="4,4,4,4";
var valid:Boolean=true;
for(var i:int=0;i<a.length-1;i++)
{
if(a.charAt(i)=="," && a.charAt(i)==a.charAt(i+1))
{
trace(a.charAt(i));
valid=false;
}
}
Only here I used strings.

Related

Read a string in AS3

I have a question regarding to my project which is how to read a string in AS3.
Actually, I have an text file named test.txt. For instance:
It consists of:
Sun,Mon,Tue,Wed,Thu,Fri,Sat
and then I want to put all of them into an array and then a string to show them in the dynamic text Box called text_txt:
var myTextLoader:URLLoader = new URLLoader();
myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(e:Event):void
{
var days:Array = e.target.data.split(/\n/);
var str:String;
stage.addEventListener(MouseEvent.CLICK, arrayToString);
function arrayToString(e:MouseEvent):void
{
for (var i=0; i<days.length; i++)
{
str = days.join("");
text_txt.text = str + "\n" + ";"; //it does not work here
}
}
}
myTextLoader.load(new URLRequest("test.txt"));
BUT IT DOES NOT show them in different line and then put a ";" at the end of each line !
I can make it to show them in different line, but I need to put them in different line in txt file and also I still do not get the ";" at the end of each line unless put it in the next file also at the end of each line.
And then I want to read the string and show an object from my library based on each word or line. for example:
//I do not know how to write it or do we have a function to read a string and devide it to the words after each space or line
if (str.string="sun"){
show(obj01);
}
if (str.string="mon"){
show(obj02);
}
I hope I can get the answer for this question.
Please inform me if you can not get the concept of the last part. I will try to explain it more until you can help me.
Thanks in advance
you must enable multiline ability for your TextField (if did not)
adobe As3 DOC :
join() Converts the elements in an array to strings, inserts the
specified separator between the elements, concatenates them, and
returns the resulting string. A nested array is always separated by a
comma (,), not by the separator passed to the join() method.
so str = days.join(""); converts the Array to a single string, and as your demand ( parameter passed to join is empty "") there is no any thing between fetched lines. and text_txt.text = str + "\n" + ";"; only put a new line at the end of the text once.
var myTextLoader:URLLoader = new URLLoader();
var days:Array;
myTextLoader.addEventListener(Event.COMPLETE, onLoaded);
function onLoaded(e:Event):void
{
days = e.target.data.split(/\n/);
var str:String;
stage.addEventListener(MouseEvent.CLICK, arrayToString);
}
myTextLoader.load(new URLRequest("test.txt"));
function arrayToString(e:MouseEvent):void
{
text_txt.multiline = true;
text_txt.wordWrap = true;
text_txt.autoSize = TextFieldAutoSize.LEFT;
text_txt.text = days.join("\n");
}
also i moved arrayToString out of onLoaded
for second Question: to checking existance of a word, its better using indexOf("word") instead comparing it with "==" operator, because of invisible characters like "\r" or "\n".
if (str.indexOf("sun") >= 0){
show(obj01);
}
if (str.indexOf("mon") >= 0){
show(obj02);
}
Answer to the first part:
for (var i=0; i<days.length; i++)
{
str = days[i];
text_txt.text += str + ";" + "\n";
}
I hope I understand you correctly..
I wrote from memory, sorry for typos if there are...
For the second part, add a switch-case
switch(str) {
case "sun":
Show(??);
break;
.
.
.
}

GoogleScript Spreadsheet Custom Function Handling a range of cells and getting their values

I have a Goggle Spreadsheet with some data, and I want to write a custom function to use in the sheet, which accepts a range of cells and a delimiter character, takes each cell value, splits it by the delimiter, and counts the total.
For example
Column A has the following values in rows 1-3: {"Sheep","Sheep,Dog","Cat"}
My function would be called like this: =CountDelimitedValues(A1:A3;",");
It should return the value: 4 (1+2+1)
The problem I am having is in my custom script I get errors like
"TypeError: cannot get function GetValues from type Sheep"
This is my current script:
function CountArrayList(arrayList, delimiter) {
var count = 0;
//for (i=0; i<array.length; i++)
//{
//count += array[i].split(delimiter).length;
//}
var newArray = arrayList.GetValues();
return newArray.ToString();
//return count;
}
I understand that the parameter arraylist is receiving an array of objects from the spreadsheet, however I don't know how to get the value out of those objects, or perhaps cast them into strings.
Alternatively I might be going about this in the wrong way? I have another script which extracts the text from a cell between two characters which works fine for a single cell. What is it about a range of cells that is different?
That's something you can achieve without using script but plain old formula's:
=SUM(ARRAYFORMULA(LEN(A1:A3)-LEN(SUBSTITUTE(A1:A3; ","; "")) + 1))
Credit goes here: https://webapps.stackexchange.com/q/37744/29140
something like this works :
function CountArrayList(arrayList) {
return arrayList.toString().split(',').length
}
wouldn't it be sufficient ?
edit Oooops, sorry I forgot the user defined delimiter, so like this
function CountArrayList(arrayList,del) {
return arrayList.toString().split(del).length
}
usage : =CountArrayList(A1:C1;",")
NOTE : in this example above it would be dangerous to use another delimiter than "," since the toString() joins the array elements with commas... if you really need to do so try using a regex to change the commas to what you use and apply the split on that.
try like this :
function CountArrayList(arrayList,del) {
return arrayList.toString().replace(/,/g,del).split(del).length
}
Another solution I have was that I needed to implicitly cast the objects in the array being passed as a string.
For example this function accepts the array of cells, and outputs their contents as a string with del as the delimiter (similar to the String.Split() function). Note the TrimString function and that it is being passed an element of the array.
function ArrayToString(array,del) {
var string = "";
for (i=0; i < array.length; i++) {
if (array[i] != null) {
var trimmedString = TrimString(array[i]);
if (trimmedString != "") {
if (string.length > 0) {
string += del;
}
string += trimmedString;
}
}
}
return string;
}
Below is the TrimString function.
function TrimString(string) {
var value = "";
if (string != "" && string != null) {
var newString = "";
newString += string;
var frontStringTrimmed = newString.replace(/^\s*/,"");
var backStringTrimmed = frontStringTrimmed.replace(/\s*$/,"");
value = backStringTrimmed;
}
return value;
}
What I found is that this code threw a TypeError unless I included the declaration of the newString variable, and added the array element object to it, implicitly casting the array element object as a string. Otherwise the replace() functions could not be called.

function within a loop within a function?

I'm coding an email verification form in 3 parts.
Part 1 - check a single character against a list of allowed characters and return true/false.
Part 2 - check a string of characters as the part before or after the '#' using a loop calling the previous function to each successive character.
Part 3 - check a complete email that it includes only one '#', the substring before and after the '#' both satisfy part 2 and the substring following the '#' has only one full stop.
I've got part 1 down but my loop for part 2 is incorrect and returning true for all input values other than a blank form. here is the code -
function isValidEmailPart(part)
{ var emailPartInput = document.getElementById("isValidPartArg").value;
var emailPartLength = alert(emailPartInput.length);
{
if (emailPartInput.length == "")
{
return (false)
}
else
{
NUMBER_OF_CHARACTERS = alert((emailPartInput.length) - 1);
var i = 0;
{for(var i=0; i<NUMBER_OF_CHARACTERS; i++)
{
function isValidEmailChar()
{ var validChars = 'a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,0,1,2,3,4,5,6,7,8,9,_,-,.,';
var emailPartInput = document.getElementById("isValidPartArg").value;
var charInput = emailPartInput.charAt(i);
var inputVar = validChars.indexOf(charInput);
if (inputVar < 0)
{
return (false)
}
}
}
return (true);
}
}
}
}
I know it must be something simple, there are no errors returning I have no idea what I'm doing wrong.
Please, consider the following things very carefully:
Define functions separately: you can call a function from another function BUT don't define a function inside a function
Make sure that your code is ok, pay attention to your code syntax: I found additional { for example. Usually your code editor highlights code syntax errors.
Pay attention to your code's indent: having a good indent helps you have a clearer view of your code and helps you find your potential code mistakes.
Review the different types of variables: in javascript, the variables can have different types: boolean, integer, float, string, etc. You can only compare variables of a same types (Do not mix carrots and potatoes!) and so, you cannot compare emailPartInput with an empty string "" for example.
Before reading the code bellow, you should try to search what was wrong it your code, and what has to be modified to make it work.
Check very carefully the comments I wrote in the code that follows (I took a lot of time to write them!)
The javascript functions:
// This functions verifies if a char 'my_char' is valid
function isValidEmailChar(my_char)
{
// 'my_char' is a i-th character of 'emailPartInput'
var output = false;
// 'validChars' is the array containing all the valid characters
var validChars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'0','1','2','3','4','5','6','7','8','9','_','-','.'];
// We want to check if 'my_char' is in the array 'validChar'
// So, for each character in the array 'validChar', we check that there's at least
// 1 character in it which is equal to 'my_char'
for(var i=0; i<validChars.length; i++)
{
// 'output' is the result that the function 'isValidEmailChar' will return
// It is initially set to "false"
// The line below means: we store in 'output'
// the result of " output OR ['my_char' EQUALS the i-th character in the array 'validChars'] ".
// Which means that, in the end, 'output' will be "true" if there's at least one i-th character
// in the array 'validChars' where 'my_char' EQUALS the i-th character in the array 'validChars'.
output = (output || (my_char == validChars[i]));
}
// We return the output
// Note: It is better to define 1 'return' and not several
return output;
}
// This function verifies if a part of Email is valid
function isValidEmailPart(emailPartInput)
{
// 'emailPartInput' is the part of email
// 'output' is your function's result to be returned
var output = false;
alert("INPUT = "+emailPartInput);
var nb_of_characters = emailPartInput.length;
alert("number of characters = "+nb_of_characters);
if (nb_of_characters != 0)
{
output = true;
var i = 0;
while(output && i<nb_of_characters)
{
// 'is_character_valid' is a boolean value which is set to:
// - true: if the i-th character of 'emailPartInput' is valid
// - false: if not valid
var is_character_valid = isValidEmailChar(emailPartInput.charAt(i));
// The line below means that we store in the variable 'ouput' the result of
// 'output' AND 'is_character_valid', which means that:
// if there's at least one 'is_character_valid' set to false
// (= one i-th character of 'emailPartInput' is not valid)
// 'output' will then be equals to false
output = output && is_character_valid;
i++;
// We remark that if 'output' is false, we quit the 'while' loop
// because finding one invalid character means that 'emailPartInput' is invalid
// so, we do not need to check the other characters of 'emailPartInput'
}
}
else
{
alert("No emailPartInput has been input");
}
// We return the output
return output;
}
Here's a working example where you can test your functions:
<HTML>
<HEAD>
<SCRIPT language="javascript">
// This functions verifies if a char 'my_char' is valid
function isValidEmailChar(my_char)
{
// 'my_char' is a i-th character of 'emailPartInput'
var output = false;
// 'validChars' is the array containing all the valid characters
var validChars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
'0','1','2','3','4','5','6','7','8','9','_','-','.'];
// We want to check if 'my_char' is in the array 'validChar'
// So, for each character in the array 'validChar', we check that there's at least
// 1 character in it which is equal to 'my_char'
for(var i=0; i<validChars.length; i++)
{
// 'output' is the result that the function 'isValidEmailChar' will return
// It is initially set to "false"
// The line below means: we store in 'output'
// the result of " output OR ['my_char' EQUALS the i-th character in the array 'validChars'] ".
// Which means that, in the end, 'output' will be "true" if there's at least one i-th character
// in the array 'validChars' where 'my_char' EQUALS the i-th character in the array 'validChars'.
output = (output || (my_char == validChars[i]));
}
// We return the output
// Note: It is better to define 1 'return' and not several
return output;
}
// This function verifies if a part of Email is valid
function isValidEmailPart(emailPartInput)
{
// 'emailPartInput' is the part of email
// 'output' is your function's result to be returned
var output = false;
alert("INPUT = "+emailPartInput);
var nb_of_characters = emailPartInput.length;
alert("number of characters = "+nb_of_characters);
if (nb_of_characters != 0)
{
output = true;
var i = 0;
while(output && i<nb_of_characters)
{
// 'is_character_valid' is a boolean value which is set to:
// - true: if the i-th character of 'emailPartInput' is valid
// - false: if not valid
var is_character_valid = isValidEmailChar(emailPartInput.charAt(i));
// The line below means that we store in the variable 'ouput' the result of
// 'output' AND 'is_character_valid', which means that:
// if there's at least one 'is_character_valid' set to false
// (= one i-th character of 'emailPartInput' is not valid)
// 'output' will then be equals to false
output = output && is_character_valid;
i++;
// We remark that if 'output' is false, we quit the 'while' loop
// because finding one invalid character means that 'emailPartInput' is invalid
// so, we do not need to check the other characters of 'emailPartInput'
}
}
else
{
alert("No emailPartInput has been input");
}
// We return the output
return output;
}
function test() {
var my_input = document.getElementById("my_input").value;
var result = isValidEmailPart(my_input);
if(result)
alert("The part of email is valid");
else
alert("The part of email is NOT valid");
}
</SCRIPT>
</HEAD>
<BODY>
Enter you Email part here:
<INPUT type="text" id="my_input" value="" />
<button onclick="javascript:test();">Check the Email part!</button>
</BODY>
</HTML>
NB: The most important is to make sure that you understand what you wrote in your code and what was wrong.
I think you know that just copying a working won't be a benefit for you.
If you read my code, I hope you spent your time to understand it and to read the comments carefully (I took a lot of time to write them! :S)
You can check free online tutorials to learn javascript too! :)
Hope this helps. If you have any questions, do not hesitate to ask, I'll be glad to help.

Restrict input to a specified language

I use a TextInput component of Flex 4.5 to enter some text in English. I use the restrict attribute to ... restrict the keyboard input to characters a-zA-Z only. The problem is that if i copy/paste a word in another language, i can then paste it into the TextInput component. Is there a way to avoid that? If no, how can i validate the input against a specified language?
I found out that the unicode set of Chinese+ language symbols is \u4E00 to \u9FFF. So i write the following:
var chRE:RegExp = new RegExp("[\u4E00-\u9FFF]", "g");
if (inputTI.text.match(chRE)) {
trace("chinese");
}
else {
trace("other");
}
But if i type in the TextInput the word 'hello' then it validates...What is the error?
Since i cannot (my fault? or a bug?) use unicode range with RegExp, i wrote the following function to check if a word is in Chinese and that's it.
private function isChinese(word:String):Boolean
{
var wlength:int = word.length;
for (var i:int = 0; i < wlength; i++) {
var charCode:Number = word.charCodeAt(i);
if (charCode <= 0x4E00 || charCode >= 0x9FFF) {
return false;
}
}
return true;
}
The String.match() method returns an array which will always test to true, even if it's empty (see docs here: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/String.html#match%28%29)
Use the RegExp.test() method instead to see if it matches:
// Check your character ranges:
//var chRE:RegExp = new RegExp("[\u4E00-\u9FFF]", "g"); // \u9FFF is unrecognised and iscausing issues.
var chRE:RegExp = new RegExp("[\u4E00]+", "g"); // This works.
if (chRE.test(inputTI.text)) {
trace("chinese");
}
else {
trace("other");
}
You'll need to check the character ranges too - I couldn't get it to match with \u9FFF in the regex.

post all values in select box /listbox

I have a selectbox on a form - which I've turned in to a list box by putting
<select id="Select1" name="D1" size="5" style="width: 220px">
I'm filling this select/listbox with values...
When I post the form how can I get all the values in the select box..is this possible or am I only able to get one that has been selected.
Trouble is I want all the values in the select (I'm not selecting any as such)
Any ideas?
Before submitting the form you can use some JavaScript to pull the items out of the select and put them into a hidden text field (as a delimited string)
For example, you can get the values using
var select1 = document.getElementById('select1');
var values = new Array();
for(var i=0; i < select1.options.length; i++){
values.push(select1.options[i].value);
}
var allValues = values.join(";");
alert(allValues);
Hope that helps.
How are you adding the values to the list box? Are they static or are they pulled from a database.
If you're pulling from the database I would create a function that you use to get the data and bind to the list box.
Then use that same function when you want to get those values after the post. You may have to use some hidden fields to pass along any parameters you use to get the values for the list box in the first place.
example:
function get_models_for_make(int make_id)
mydata_rs = SELECT name, id FROM models WHERE make_id = make_id
return mydata_rs
end
so you could use this data to bind the objects to your listbox and also use it to get the values later that you did bind to your list box.
for (int i = source.Items.Count - 1; i >= 0; i--)
{
ListItem item = source.Items[i];
if (moveAllItems)
item.Selected = true;
if (item.Selected)
{
// if the target already contains items, loop through
// them to place this new item in correct sorted order
if (target.Items.Count > 0)
{
for (int j = 0; j < target.Items.Count; j++)
{
if (target.Items[j].Text.CompareTo(item.Text) > 0)
{
target.Items.Insert(j, item);
item.Selected = false;
break;
}
}
}
// if item is still selected, it must be appended
if (item.Selected)
{
target.Items.Add(item);
item.Selected = false;
}
// remove the item from the source list
source.Items.Remove(item);
}
}