I want to define a function for range validator using java script. I define it but it just work for integers. my question is that what can be in min and max value? how to check min and max value if they are string or other types?
here is my function:

function minmax(value) {
var min = document.getElementById("min_val").value;  
var max = document.getElementById("max_val").value;
if (min <= max) {
    if (parseInt(value) < min || isNaN(value)) {
        alert("input shouldn't less than  " + min);
    }
    else if (parseInt(value) > max) {
        alert("input shouldn't more than  " + max);
    }
}
else
    alert("The MaximumValue cannot be less than the MinimumValue  of RangeValidator");

}

有帮助吗?

解决方案

Plain old JavaScript uses the typeof operator to determine the underlying type of a variable or value and returns the string value of the type, like this:

typeof 37 would return 'number'
typeof 3.14 would return 'number'
typeof "37" would return 'string'
typeof "" would return 'string'
typeof function() {} would return 'function'
typeof true would return 'boolean'
typeof false woulld return 'boolean'
typeof undefined would return 'undefined'
typeof {1, 2, 3} would return 'object'
typeof null would return 'object'

I believe the only two types you should care about are 'number' and 'string', because you can coerce a 'string' to a 'number'.

I would put a check at the top of your function to see if the min and max are both either 'number' or 'string' and if not, then bail out of your function.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top