0

I am using this in one of my asp.net mvc 3 views :

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        $('.YesNoNotApplicable').change(function () {
            if ($(this).val() === '2') {
                $(this).closest('td').next('td').find('input').show();
            }
            else {
                $(this).closest('td').next('td').find('input').hide();
            }
        });
        $('#submitDocument').click(function () {
            if ($(".checkString16").val().length > 16) {
                alert("The text can be up to 16 symbols");
                return false;
            }
            else if (!$.isNumeric($(".checkULong").val())) {
                alert("Insert integer");
                return false;
            }
            else if (!$(".checkFloat").val().match('^[0-9]*\.[0-9]*$')) {
                alert("Insert float");
                return false;
            }
            return true;
        });
    });
</script>

The problem here is that I get very random results. If my integer check is uncommented like now I get the integer alert all the time. If I comment it then sometimes the float check works, sometimes now, and if it works the first time, then I get the error constantly even though I have changed the value to float.

Leron
  • 9,546
  • 35
  • 156
  • 257

1 Answers1

1

I am going to recommend you another way of checking the number type in javascript.

Firstly create a namespace for math functions like the following:

mathFunctions = {}; 

By using namespaces (actually js objects) you make your code more organized.

Then you need to create some methods that will perform the validation checks that are required by your program:

mathFunctions.isInt = function(value) {
    return typeof value === 'number' && value % 1 == 0;
}

mathFunctions.isFloat = function(value) {
    return typeof value === 'number' 
        && parseFloat(value) == parseInt(value, 10) && !isNaN(value);
}

So whenever you need to check a math value, call these methods and you are going to get proper results. Look at the following validation code for example:

try {
    if ($(".checkString16").val().length > 16) {
        throw "The text can be up to 16 symbols";
    } else if (!mathFunctions.isInt($(".checkULong").val())) {
        throw  "Insert integer";
    } else if (!mathFunctions.isFloat($(".checkFloat").val())) {
        throw "Insert float";
    }
    validationResult = true;  
} catch(exc) {
    alert(exc)
    validationResult = false;
}
return validationResult;

You can find more on the method implementation on this post : How do I check that a number is float or integer?

EDIT

You can see in this page http://api.jquery.com/jQuery.isNumeric/ that $.isNumeric() is returning TRUE even on float values.

Community
  • 1
  • 1
Alex Tselegidis
  • 155
  • 1
  • 12