Tiger
Tiger

Reputation: 139

My javascript validation of number function does not work correctly

function ValidateShippedQuantity() {
    var shippedQty = jQuery("#txtShippedQuantity").val();
    shippedQty = shippedQty.toString();
    for (i = 0; i < shippedQty.length; i++) {
        var c = shippedQty.charAt(i);
        if (isNaN(c)) //(!(/^\d+$/.test(shippedQty))) 
        {
            alert("Only Numeric Values Allowed");
            //x.focus();
            return false;
        }
    }
    return true;
}

What I want is to check the textbox that contains only numeric value. And the function above either isNaN or /^\d+$/.test() does not work since it always returns false whatever I enter such as "1" or "10". Even weird, the isNaN used to work for a while. And then it just did not work later no matter what I undid what I did.

The button which called the validation function, is within a Gridview.

<EditItemTemplate>
 <asp:LinkButton ID="btnUpdTrk" runat="server" Text="Update" CommandName="Update"
    OnClientClick="javascript:return ValidateShippedQuantity();" CausesValidation="false" />
</EditItemTemplate>

The textbox of txtShippedQuantity,

<asp:TemplateField HeaderText="Shipped&nbsp;Qty">
   <ItemTemplate>
     <asp:Label ID="lblShippedQuantity" runat="server" Text='<%#Eval("ShippedQuantity")%>'></asp:Label>
   </ItemTemplate>
   <EditItemTemplate>
     <asp:TextBox runat="server" ID="txtShippedQuantity" Width="50px" Text='<%#Eval("ShippedQuantity")%>' />
   </EditItemTemplate>
</asp:TemplateField>

For those who has the same problem, the answer or solution is below. This is the real happiness of solving the problem yourself after disappointing procedure. @cymen gives me a little help. And I change one line to his codes.

        $(document).ready(function () {
        $('#btnUpdTrk').on('click', ValidateShippedQuantity);
        });
        function ValidateShippedQuantity() {
        var shippedQty = document.getElementById('ContentPlaceHolder1_gvTrkInfo_txtShippedQuantity_0').value;
        var shippedQtyNumber = parseInt(shippedQty, 10);
        if (shippedQtyNumber.toString() !== shippedQty) {
            alert("Only Numeric Values Allowed for Tracking #.");
            return false;
        }
        return true;
    }

The second line from @cymen codes, is the cause of problem for my aspx page, at least after editing that I got what I wanted. I think it's the getTlementById part. After finding the correct ID for txtbox txtShippedQuantity from the google chrome developer tool.

Upvotes: 1

Views: 661

Answers (7)

Ruan Mendes
Ruan Mendes

Reputation: 92334

All you need is something that tests if all the characters are digits. No need to loop through each character, just use regular expressions http://jsfiddle.net/4nXT3/ This will not be as easy if you need to support floats or other input formats, in which case you need something more complicated like what was suggested by Cymen

function ValidateShippedQuantity() 
    var input = jQuery("#txtShippedQuantity").val();
    if ( !/^\d+$/.test(input) )  {
        alert('Only Numeric Values allowed')
        return false;
    }
    return true
}

Upvotes: 0

Trevor Dixon
Trevor Dixon

Reputation: 24392

http://jsfiddle.net/4nXT3/

function ValidateShippedQuantity() {
    var shippedQty = jQuery("#txtShippedQuantity").val();
    if (isNaN(shippedQty)) {
        alert('Only Numeric Values Allowed');
        return false;
    }
    return true;
}

Update: read the comments to know why this bad.

Upvotes: 0

Andy Lastname
Andy Lastname

Reputation: 86

function ValidateShippedQuantity() {
    var reg = new RegExp("^[0-9]+$");
    return reg.test(jQuery("#txtShippedQuantity").val());
}

Upvotes: 0

defau1t
defau1t

Reputation: 10619

You could use the below approach, that said I don't see anything wrong with your approach to validate this.

<html>
<head>
    <title></title>
    <meta charset="UTF-8" />
        <script type="text/javascript">
        function ValidateShippedQuantity() { 
    var shippedQty = jQuery("#txtShippedQuantity").val(); //alert(shippedQty);
    shippedQty = shippedQty.toString();
    for (i = 0; i < shippedQty.length; i++) {
        var c = shippedQty.charAt(i);
        if (isNaN(c))         {
            alert("Only Numeric Values Allowed");
            //x.focus();
            return false;
        }

    }
    if(shippedQty.length == 0)
        {
            alert("Field can't be blank");
        }
    return true;
    $("form").submit();
}
    </script>
</head>
<body>
    <form method="GET">
    <input type="text" id="txtShippedQuantity" /><br /><br />
    <input type="submit" value="Validate" onclick="ValidateShippedQuantity()" />
</form>
</body>
</html>

I think you are making the mistake by not being able to call the function properly.

I have added a demo too at JSFIDDLE

Upvotes: 0

Cymen
Cymen

Reputation: 14429

You can use parseInt to parse the input string to number and then compare the number to the original string:

var input = '5';
var number = parseInt(input, 10);
if (number.toString() === input) {
    // valid
} else {
    // invalid
}

So I would write you function as:

function ValidateShippedQuantity() {
    var shippedQty = jQuery("#txtShippedQuantity").val();
    var shippedQtyNumber = parseInt(shippedQty, 10);
    if (shippedQtyNumber.toString() !== shippedQty) {
        alert("Only Numeric Values Allowed");
        return false;
    }
    return true;
}

Here is a functioning demo (with additional alert on valid): http://jsfiddle.net/S4CQT/

Note that this will fail if they enter 1,000 as it will check if '1000' equals '1,000'. So if you want to support commas, you have a couple of options but a quick way (that would consider 10,00 to be valid), would be to change the statement in the if to this:

shippedQtyNumber.toString() !== shippedQty.replace(',', '')

Another potential failure is if you allow non-whole numbers (like 10.5). In that case, look into parseFloat.

Upvotes: 2

Matthew Shea
Matthew Shea

Reputation: 567

Use the ASP.NET validators

<asp:RegularExpressionValidator ValidationExpression="^\d+$" 
    ControlToValidate="txtShippedQuantity" runat="server" 
    Text="Must be a number" Color="Red" Display="Dynamic" />

This will prevent a postback client side if it does not match the specified regular expression.

Alternatively, you can use the RangeValidator

<asp:RangeValidator 
    MinimumValue='<%# Int32.MinValue %>' 
    MaximumValue='<%# Int32.MaxValue %>' 
    ControlToValidate="txtShippedQuantity" 
    runat="server" />

Upvotes: 1

epascarello
epascarello

Reputation: 207557

Um, shouldn't

if (isNaN(shippedQty))

be

if (isNaN(c))

And why are you looping when a regular expression can check for numbers?

Upvotes: 0

Related Questions