30 Days of Mootools 1.2 Tutorials - Day 8 - Input Filtering Part I (Numbers)

- admin

Hey folks, today we’re going to starting looking at how Mootools can make filtering user input a breeze. We’re going to be starting off with some basic number filtering today, and digging into the world of string filtering tommorrow. If you haven’t already checked out the rest of the 30 Days of Mootools tutorials, I’d highly recommend doing so before continuing on.

NOTE: Input filtering in Javascript is to ensure that your code runs smoothly, it should NOT be used as a substitute for the server side input filtering required to protect your applications against injection attacks.

Numbers

On Day 4 we ended with an example that took RGB values from textboxes and used them to change the background of the page, today we’re going to start by going over some of the code from that example and expanding upon it.

rgbToHex()

Technically speaking, the rgbToHex() function actually belongs to the Array collection. Since it’s an array function built to deal with numbers, we’re going to tackle it today. Functionally, rgbToHex() is pretty straightforward to use:

function changeColor(red_value, green_value, blue_value){
	var color = [red_value, green_value, blue_value].rgbToHex(); 
	alert('Converts to : ' + color); 
}
 
changeColor('28', '17', '47')



This works perfectly, as long as the values for red, green, and blue are numbers. Check out the behavior when you pass it something unexpected :



The NaN you see at the end there stands for Not a Number. If you’re hard coding color values into the array, this situation probably isn’t going to come up. If you’re getting input from any other source though, you’re most likely going to run into situations where you have to deal with invalid input.

toInt()

So now, we need a way to make sure that the rgbToHex() function is only getting numbers passed to it - that is where the toInt() function comes in. toInt() is another relatively straightforward function. You call it on a variable and it does its best to get a regular integer from whatever the variable contains.

var toIntDemo = function(make_me_a_number){
	var number = make_me_a_number.toInt();
	alert ('Best Attempt : ' + number);
}



As you can see, toInt() can’t handle every conceivable situation, but thanks to another piece of Mootools coolness called $type(), we can deal with that problem as well.

$type()

$type() is another one of the incredibly straightforward and useful goodies from the Mootools crew. It examines whatever variable you pass it, and returns a string telling you what type of variable it is:

var checkType(variable_to_check){
	var variable_type = $type(variable_to_check);
	alert("Variable is a : " + variable_type);
}



There’s a buttload of other types that $type() detects - you can get a full list of them in the Core.$type() documentation. For now though, all we’re really worried about is detecting integers. If we take $type() and throw into the toIntDemo() function we can very easily deal with input that toInt() can’t handle :

var toIntDemo = function(make_me_a_number){
	//Try to make the input number
	var number = make_me_a_number.toInt();
 
	//If That didn't work, set number to 0
	if ($type(number) != 'number'){number = 0;}
	alert('Best Attempt : ' + number);
}



When we pull it all together into changeColor(), we get a solution that works almost perfectly :

var changeColor_2 = function(red_value, green_value, blue_value){
	//Try to make sure everything is an integer
	red_value = red_value.toInt();
	green_value = green_value.toInt();
	blue_value = blue_value.toInt();
 
	//Set default values on anything thats Not a Number
	if ($type(red_value)   != 'number'){red_value = 0;}
	if ($type(green_value) != 'number'){green_value = 0;}
	if ($type(blue_value)  != 'number'){blue_value = 0;}
 
	//Calculate hex value
	var color = [red_value, green_value, blue_value].rgbToHex(); 
	alert('Converts to : ' + color); 
}



The last function is passing rgbToHex() numbers outside of the RGB range of 0 - 255, which quite dutifully converts the value into it’s hex equivalent. Unfortunately this means that if we receive a number outside of that range as input, we aren’t going to be able to get a valid hex color value. Fortunately, there’s of one more piece from the Mootools kit, we can throw in to take care of this problem too.

limit()

The Mootools limit() function is pretty no frills. You call it on a number with the lower and upper bounds you want to limit the number to as arguments, and if that number is outside of the range you define, it rounds appropriately. It’s important to keep in mind that limit REQUIRES an integer to function, so it’s a generally a good idea to use toInt() on something you’re assuming to be a number before using limit (or anything else in the Number Collection).

var limitDemo = function(number_to_limit){
	//Do our best to get an integer
	number_to_limit = number_to_limit.toInt();
 
	//Get the limited value
	var limited_number = number_to_limit.limit(0, 255);
	alert("Number Limited To : " + limited_number);
}



Stick a Fork in it

var changeColor = function(red_value, green_value, blue_value){
	//Try to make sure everything is an integer
	red_value   = red_value.toInt();
	green_value = green_value.toInt();
	blue_value  = blue_value.toInt();
 
	//Set default values on anything thats Not a Number
	if ($type(red_value)   != 'number'){red_value = 0;}
	if ($type(green_value) != 'number'){green_value = 0;}
	if ($type(blue_value)  != 'number'){blue_value = 0;}
 
	//Limit Everything to the RGB Scale (0 - 255)
	red_value   = red_value.limit(0, 255);
	green_value = green_value.limit(0, 255);
	blue_value  = blue_value.limit(0, 255);
 
	//Calculate hex value
	var color = [red_value, green_value, blue_value].rgbToHex(); 
	alert('Converts to : ' + color); 
}



To Learn More

Download a zip with everything you need to get started

Standard Number Functionality
Mootools Number Functionality
Mootools Array Functionality

Tomorrow’s Tutorial

Input Filtering Part 2 -Strings

Requests?

While we’re starting to get into more complex areas of the library, we’ve still got plenty of time left to fit in any topics or areas you’re interested in. If there’s something you’d like to learn to do with Mootools, please let us know and we’ll do our best to work it in to the schedule.

Bookmark and Share

Comments (8) Trackbacks (7)
  1. Brad


    Hello,

    Thanks for the great tuts, they are clearing ou alot of things for me, what I would like to see being explained is for example, how it's possible to make colums, e.g 1,2,3,4 and the width of those colums are adjustable through a scroller.. and mayeb some more in depth about drag and drop ? :)

    btw for an example of what I mean with the colums it can be found at netvibes.com :) the colums there can be made wider etc =]

    once again thanks for the tuts
  2. Louis


    The more a see your work, the more I wonder why you are publishing it on this very site, instead of comitting all the the official Mootools docs. There may be less glory and less pagerank, but in the end you would be a greater hero.

    Great work though.

    Note: little typo at the beginning : "you’re code" -> "your code".
  3. Troy


    @1 - thanks for the feedback, we have a drag and drop tutorial scheduled for later this week... as far as the column width, why don't you check out "Day 7 - setting and getting style properties" and "Day 5 - events." Between the two of those tutorials, i'll bet you could piece something together :)

    @2 - we would happy to contribute in a more official way, but the way I understand it, the docs need to be a full picture, and are generally intended for people with at least some previous javascript xp, whereas this series is targeted toward people with less experience.
  4. lauren


    @2: A few additional points to consider:

    We were asked by Pradeep, one of our readers, to create these tutorials. No one's trying to be a hero--we're just trying to be helpful.

    There are much easier ways to get PageRank. The guys have already spent a ridiculous amount of time on these tutorials.

    Thanks for sharing your thoughts :)
  5. Vin Thomas


    Thanks a ton for all these tutorials. I guess as a designer, my request would be to have more practical examples that I would use in my sites. Similar to what webdesignerwall did with jquery.

    Thanks again! I can't imagine the time that goes into this! Know that it is VERY appreciated!
  6. Louis


    @Lauren: Yes, totally. The tone of my previous comment might sound a little critic, but it is not. The "hero" for example was more a compliment than a sarcastic remark :)

    These tutorials are pretty exhaustive, and I know that it require *a lot* of time the write things like these. Though, I still think you should come on IRC talk to the devs, and propose them to comit your work to the official docs.

    @Troy: if I take day8 tutorial for example, it's a lot like the docs : a function, a definition of that function, and a working example. It doesn't seem to me that it a different approch or philosophy. These tutorials would really boost the docs that lacks examples and more detailed definitions.

    Once again, I'm thankful. Also, your "tell us what you'd like us to talk about" philosophy is very generous; I like it :)
  7. Troy


    @5 - Thanks Vin, we intend to get more practical as we go, start doing mini projects that are useful and highlight some of Mootools functionality. There is probably still a good week of these kinds of tutorials left tho, we really want to make sure everyone is familiar with a good portion of the library and a few basic programming concepts. Someone else mentioned that tutorial as an example, I will be sure to take a good look over it when we get to that stage.

    @6 - We want to keep this as participatory as possible. We are pretty much just fans of the library, and we thought this would be a good way to engage the community, share some knowledge, and learn more about mootools (especially from all the great comments and feedback). As far as the examples in the docs, I will let the devs know they are they welcome to take any examples from the tutorial that they think would be useful to them. Thanks for the suggestion :)
  8. Graeme


    These are really great tutorials.
    I know JS functionality pretty well with the exception of the fx modules.

    However, this toolset and tutorials is making me slightly excited in a geeky kinda way.

    Many thanks.


Leave a Reply