Search code examples
javascriptjqueryajaxwebmethod

textbox values are taking string value so now how to validate input should be integer not string


$(document).ready(function() {


      Function arraysort(text) {

          $.ajax({
            type: "POST",
            url: "default.aspx/sort",
            data: JSON.stringify({
              arr: text.split(',')
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
              //some code here
            }
          });
          If

user give input into textbox as string then alert that please enter integer values and if it is an integer value then alert that input should be greater than one and integer should be comma seperated such as 100,23,12,1 and if single value or string or integers are not comma seperated then dont sort array .but here my textbox values are taking already string value and then passing this string value to the webmethod side.now how can I make sure that in textbox value should be integer but it already taking string value


Solution

  • Client Side (Javascript and jQuery):

    use isNaN it was designed for this

    $(function() {
      $("#btn").on("click", function() {
        if (isNaN($("#text1").val())){
            alert("Text Value is Not a number");
            return;
        } else {
        // It's a number, add your code here
        }
      });
    });
    

    isNaN stand for "is not a number"

    isNaN("text") // true
    isNaN(1) // false
    isNaN("1") // false
    

    if you want to do Math with $("#text1").val() you can use Number($("#text1").val())

    the code above will validate the value on client side and send to server only if valid

    Server Side (C#):

    as of your question on how to validate on server side using C# you can use

    int n;
    bool isNumeric = int.TryParse("123", out n);
    

    also look here: