base test

by pat spag

HTML

<div>Convert an integer value to a string value
    <BR/>Assuming 16 bit integers
    <BR/>Number: the number to be converted
    <BR/>Base: the base to use in conversion, has to be between 2 and 36
    <BR/>
</div>
<BR/>
<div></div>Number:&nbsp;
<input name="numberTxt" type="text" maxlength="512" id="numberTxt" class="numberTxt" value='-1' />&nbsp;Base:
<input name="baseTxt" type="text" maxlength="512" id="baseTxt" class="baseTxt" value="16" />
<button onclick="parse();">Evaluate</button>
<div/>Result:&nbsp;&nbsp;&nbsp;&nbsp;
<input name="resultTxt" type="text" maxlength="512" id="resultTxt" class="resultTxt" />
<div/>
<span id="error"></span>

CSS

body {
    font-family: Helvetica, Verdana
}
p {
    padding: 7px 10px;
}
#error {
    color: red;
}

JavaScript

var ws = /^\s+$/;
var validInputs = true;
var maxInt = 2147483647;
var minInt = -2147483648;

//Parse string input and convert it to a number
function parse() {
    if (validateInputs()) {
        itoa(number, base);
    }
}

//Make sure both Base and Number are valid integers within the expected range
//Returns true if inputs are valid, false otherwise
function validateInputs() {
    validInputs = true;
    document.getElementById('error').innerText = '';
    var numberStr = document.getElementById('numberTxt').value;
    var baseStr = document.getElementById('baseTxt').value;

    number = validateInt(numberStr);
    if (!validInputs) {
        error('FAILED: Invalid Number');
        return false;
    }

    base = validateInt(baseStr);
    if (!validInputs) {
        error('FAILED: Invalid Base');
        return false;
    }

    //base has to be between 2-36
    if (base < 2 || base > 36) {
        error("Base must be between 2 and 36");
        return false;
    }
    return true;
}

//Validate that a string can be converted to an int
//Returns the converted number
//If validation fails validInputs is set to false
function validateInt(str) {
    //Do not accept empty or whitespaces (Number function accepts them)
    if (str == "" || ws.test(str)) {
        error("Number cannot be empty or whitespaces");
        return -1;
    }

    var intValue = Number(str);
    if (intValue > maxInt || intValue < minInt) {
        error("'" + str + "' is not a valid integer");
        validInputs = false;
        return -1;
    }

    //Make sure we got valid integers
    if (isNaN(intValue)) {
        error("'" + str + "' is not a valid integer");
        validInputs = false;
        return -1;
    }

    //Make sure this is a valid int
    if (parseInt(str) != intValue) {
        error("'" + str + "' is not a valid integer");
        validInputs = false;
        return -1;
    }

    return intValue;
}

//itoa conversion, it takes a valid integer and converts it to a...