Validating data with built-in functions



Built-in functions in JavaScript

JavaScript provides built-in functions to evaluate data type. Some functions are provided directly within JavaScript; others are provided by the jQuery library.

The isNaN function provides a way to evaluate whether the value passed into it isn’t a number. The function returns true; if it is a number, it returns false.

The following code demonstartes the isNaN function:

<body>
<form>
    <label for="validateNumber">Number : </label>
    <input type="text" id="validateNumber" /> <br />
    <div id="div1"></div><br />
    <button onclick="validateNr();">Evaluate</button>
</form>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script>
<script type="text/javascript">
    var validateNr = function () {
            var value = $('#validateNumber').val();
            if (isNaN(value)) {
                //handle the non number value
                alert(value + " is not a number!!!");
            }
            else {
                //proceed with the number value
                alert(value + " is a number!!!");
            }
    }
</script>
</body>

The opposite of the isNaN function is the isFinite function. The isFinite function is used in the same way but returns true if the value is a finite number and false if it’s not.

Using the eval function

The eval function is used to run JavaScript dynamically. It takes a string as a parameter and runs it as a JavaScript function.

Never use the eval function against any data provided by an external source over which you don’t have 100 percent control.

The following code demonstrates the eval() function:

<body>
<button onclick="myEval()">Evaluate with eval()</button>
<span id="showHere"></span>
<script>
    function myEval() {
        var x = 10;
        var y = 20;
        var a = eval("x * y") + "<br>";
        var b = eval("2 + 2") + "<br>";
        var c = eval("x + 17") + "<br>";
        var result = a + b + c;
        document.getElementById("showHere").innerHTML = result;
    }
</script>
</body>

Using iFrames

iFrames open up a new opportunity to attackers. Search engines provide a plethora of results dealing with exploits regarding the use of iFrames.

The sandbox attribute should always be used to restrict what data can be placed into an iFrame.

The following Table lists the available sandbox attribute values:

Value Description
" " An empty string applies all restrictions. This is the most secure.
allow-same-origin iFrame content is treated as being from the same origin as the containing HTML document.
allow-top-navigation iFrame content can load content from the containing HTML document.
allow-forms iFrame can submit forms.
allow-scripts iFrame can run script.

PROMOTIONS