1
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.

3
  • I believe the line should be var c = shippedQty.charAt(i); if (isNaN(c)) Commented Feb 21, 2013 at 19:59
  • @BradM it's a typo. changed.thanks. Commented Feb 21, 2013 at 20:06
  • No need to test each character, just need return /^\d+$/.test(jQuery("#txtShippedQuantity").val()) Commented Feb 21, 2013 at 20:26

7 Answers 7

2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

thanks. it's whole numbers. and i tried your codes which has the same issue. no luck.
There is a problem with how you are hooking it up then. Here is a jsfiddle that shows it working: jsfiddle.net/S4CQT
yeah. i added more details above.
i still do not know why clearly. but i fix the problem. see my problem description above.
1

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" />

13 Comments

This should be a suggestion, since it is a workaround (a fine one)
How is it a workaround? It's the standardized built-in way to validate controls in ASP.NET
The question is about the JS, you can workaround having to write your own JS by using ASP.NET validators
i tried your way.but this does not work with my codes. the validation should be triggered after a linkbutton is pressed. that's why i used javascript to stop the action before taking effect.
The question is also tagged as ASP.NET, meaning the standardized ASP.NET way is a valid answer.
|
0

Um, shouldn't

if (isNaN(shippedQty))

be

if (isNaN(c))

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

Comments

0

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

Comments

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

Comments

0

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.

8 Comments

isNaN() called on a string is never going to return true, you proably meant isNan(parseInt(shippedQty), 10)
In Chrome console, isNaN("10a") -> true
I stand corrected. But I'm reluctant to upvote because it seems that isNaN() does return a lot of false positives, and should be avoided developer.mozilla.org/en-US/docs/JavaScript/Reference/… "The next version of ECMAScript (ES6) contains the function Number.isNaN... a reliable way to test whether x is NaN or not... as the result is not subject to the false positives that make isNaN unreliable.
This is another example from the MDN page: "This is a false positive and the reason why isNaN is not entirely reliable"isNaN("blabla") => true "blabla" is converted to a number. Parsing this as a number fails and returns NaN"
That's good; that's the desired behavior for his purposes. The one that's troubling is isNaN(' ') -> false.
|
0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.