-3

I am currently using the script below to take my inputs and convert them to what I want with some validation included. I have got my server side validation set up and would like to have some client side also, I have validated the lengths of the inputs but now need to ensure that they only contain numbers. This is for the Variables day, month and year. I have tried using IsNumeric() but to no avail

<script type="text/javascript">
function timeMachine() {

    var day     = $("#date_day").val();
    var month = $("#date_month").val();
    var year    = $("#date_year").val();

    if (day == "" && month == "" && year != ""){
        if (year.length != 4){
            alert("Please enter a valid year!");
        } else{
            window.location = "/date/" + year ;
        }   
    } else if (day == "" || month == "" || year == ""){
        alert("Please enter a full date!");
    } else{
        var myDate = new Date(year, month-1, day);

        var monthNames = [ "january", "february", "march", "april", "may", "june","july", "august", "september", "october", "november", "december" ];   

        window.location = "/date/" + year + "/" + monthNames[myDate.getMonth()] + "/" + day;
    }
    return false;
}
</script>

Thoughts?

L. Smith
  • 105
  • 3
  • 10

2 Answers2

4

Simple way, if you are supporting modern browsers, use:

<input type="number" />

If you can use JavaScript (and jQuery), you can set up an event:

$(input).keydown(function (e) {
  if (e.keyCode >= 48 && e.keyCode <= 57) { //0-9 only
    return;
  }
  return false;
});

Else, at the final level, you may use:

/^\d+$/.test(input.value);
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
1

Try the below function:

function isNumber( num ) {
    return ! isNaN( parseFloat( num ) ) && isFinite( num );
}
web-nomad
  • 6,003
  • 3
  • 34
  • 49