How to validate type of collections?












3















How can I validate and catch collection type conversion (JSON string array to C# long collection) for my System.Web.Http.ApiController class (before the model is initialized if possible)?



I want to validate and catch any non-numeric elements in the JSON array to be return as a bad request response (maybe somehow with data annotation).



When non-numeric JSON elements are included (to be converted to long collection), they fail to parse and get stripped before the model is passed to the ApiController method. Given the classes below, a valid input should contain only numeric values for "PerferredNutTypes" and "GeographyIDs".



Classes



public class SquirrelController : ApiController
{
[HttpPost]
[Route("api/squirrels/search")]
[SwaggerResponse(HttpStatusCode.OK, Type = typeof(SquirrelsResponse))]
public HttpResponseMessage Squirrels(SquirrelsRequest model)
{
// model already parsed by the time breakpoint reaches here and non-convertable elements already stripped

...
...
...

SquirrelsResponse results = Targeting.SearchForSquirrels(model);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}

public class SquirrelsRequest
{
public SquirrelsRequest() {}

public List<long> PreferredNutTypes { get; set; } = new List<long>();
public GeographySearch geographySearch { get; set; } = new GeographySearch();
}

public class GeographySearch
{
public GeographySearch() {}

public BooleanOperator Operator { get; set; } = BooleanOperator.OR;
public List<long> GeographyIDs { get; set; } = new List<long>();
}

public enum BooleanOperator
{
AND,
OR
}


Examples:



//"Toronto" sould be an invalid input when converting from JSON string array to c# long collection.
{
"PreferredNutTypes": [34,21],
"GeographySearch": {
"Operator": 1,
"GeographyIDs": ["Toronto"]
},
}

// This is what the model currently looks like in public HttpResponseMessage Squirrels(SquirrelsRequest model)
new SquirrelsRequest()
{
PreferredNutTypes = new List<long>() { 34, 21 },
GeographySearch = new GeographySearch()
{
Operator = 1
GeographyIDs = new List<long>()
}
}


Expectations:




  • Ideally catch any non-numeric values and return them as a bad request. Similar to how you can validate to how you use use data annotations to validate range.

  • Data annotation solution acceptable.

  • Ideally a clearer approach than accessing ModelState and parsing the error's message/key.

  • Ideally can be generically applied to any collection.


  • Things I've attempted:




  • Tried custom data annotation validator, but can only access the values after it's been parsed.

  • Tried accessing validation errors via HttpActionContext's ModelState but at best, I can only get these values...


  • System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.Message => "Error converting value "sonali7678687" to type 'System.Int64'. Path 'subjectSearch.writingAbout[0]', line 6, position 36."
    System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.InnerException.Message => "Input string was not in a correct format."


    ... surely there must be a better way of validating?



    UPDATE 1:
    Rephrased question to make explanation and intent more clear.










    share|improve this question




















    • 1





      The ModelState errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value of GeographyIDs is invalid) so its not clear what you are expecting or want to do.

      – user3559349
      Nov 19 '18 at 22:15











    • I think you can get the current value from Request["GeographySearch.GeographyId"], but I would just look at ModelState.Where(m => m.Errors.Count > 0) and return a generic Response.StatusCode = 404 if the result is not null to keep it simple.

      – Kristianne Nerona
      Nov 20 '18 at 0:16


















    3















    How can I validate and catch collection type conversion (JSON string array to C# long collection) for my System.Web.Http.ApiController class (before the model is initialized if possible)?



    I want to validate and catch any non-numeric elements in the JSON array to be return as a bad request response (maybe somehow with data annotation).



    When non-numeric JSON elements are included (to be converted to long collection), they fail to parse and get stripped before the model is passed to the ApiController method. Given the classes below, a valid input should contain only numeric values for "PerferredNutTypes" and "GeographyIDs".



    Classes



    public class SquirrelController : ApiController
    {
    [HttpPost]
    [Route("api/squirrels/search")]
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(SquirrelsResponse))]
    public HttpResponseMessage Squirrels(SquirrelsRequest model)
    {
    // model already parsed by the time breakpoint reaches here and non-convertable elements already stripped

    ...
    ...
    ...

    SquirrelsResponse results = Targeting.SearchForSquirrels(model);
    return Request.CreateResponse(HttpStatusCode.OK, results);
    }
    }

    public class SquirrelsRequest
    {
    public SquirrelsRequest() {}

    public List<long> PreferredNutTypes { get; set; } = new List<long>();
    public GeographySearch geographySearch { get; set; } = new GeographySearch();
    }

    public class GeographySearch
    {
    public GeographySearch() {}

    public BooleanOperator Operator { get; set; } = BooleanOperator.OR;
    public List<long> GeographyIDs { get; set; } = new List<long>();
    }

    public enum BooleanOperator
    {
    AND,
    OR
    }


    Examples:



    //"Toronto" sould be an invalid input when converting from JSON string array to c# long collection.
    {
    "PreferredNutTypes": [34,21],
    "GeographySearch": {
    "Operator": 1,
    "GeographyIDs": ["Toronto"]
    },
    }

    // This is what the model currently looks like in public HttpResponseMessage Squirrels(SquirrelsRequest model)
    new SquirrelsRequest()
    {
    PreferredNutTypes = new List<long>() { 34, 21 },
    GeographySearch = new GeographySearch()
    {
    Operator = 1
    GeographyIDs = new List<long>()
    }
    }


    Expectations:




  • Ideally catch any non-numeric values and return them as a bad request. Similar to how you can validate to how you use use data annotations to validate range.

  • Data annotation solution acceptable.

  • Ideally a clearer approach than accessing ModelState and parsing the error's message/key.

  • Ideally can be generically applied to any collection.


  • Things I've attempted:




  • Tried custom data annotation validator, but can only access the values after it's been parsed.

  • Tried accessing validation errors via HttpActionContext's ModelState but at best, I can only get these values...


  • System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.Message => "Error converting value "sonali7678687" to type 'System.Int64'. Path 'subjectSearch.writingAbout[0]', line 6, position 36."
    System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.InnerException.Message => "Input string was not in a correct format."


    ... surely there must be a better way of validating?



    UPDATE 1:
    Rephrased question to make explanation and intent more clear.










    share|improve this question




















    • 1





      The ModelState errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value of GeographyIDs is invalid) so its not clear what you are expecting or want to do.

      – user3559349
      Nov 19 '18 at 22:15











    • I think you can get the current value from Request["GeographySearch.GeographyId"], but I would just look at ModelState.Where(m => m.Errors.Count > 0) and return a generic Response.StatusCode = 404 if the result is not null to keep it simple.

      – Kristianne Nerona
      Nov 20 '18 at 0:16
















    3












    3








    3








    How can I validate and catch collection type conversion (JSON string array to C# long collection) for my System.Web.Http.ApiController class (before the model is initialized if possible)?



    I want to validate and catch any non-numeric elements in the JSON array to be return as a bad request response (maybe somehow with data annotation).



    When non-numeric JSON elements are included (to be converted to long collection), they fail to parse and get stripped before the model is passed to the ApiController method. Given the classes below, a valid input should contain only numeric values for "PerferredNutTypes" and "GeographyIDs".



    Classes



    public class SquirrelController : ApiController
    {
    [HttpPost]
    [Route("api/squirrels/search")]
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(SquirrelsResponse))]
    public HttpResponseMessage Squirrels(SquirrelsRequest model)
    {
    // model already parsed by the time breakpoint reaches here and non-convertable elements already stripped

    ...
    ...
    ...

    SquirrelsResponse results = Targeting.SearchForSquirrels(model);
    return Request.CreateResponse(HttpStatusCode.OK, results);
    }
    }

    public class SquirrelsRequest
    {
    public SquirrelsRequest() {}

    public List<long> PreferredNutTypes { get; set; } = new List<long>();
    public GeographySearch geographySearch { get; set; } = new GeographySearch();
    }

    public class GeographySearch
    {
    public GeographySearch() {}

    public BooleanOperator Operator { get; set; } = BooleanOperator.OR;
    public List<long> GeographyIDs { get; set; } = new List<long>();
    }

    public enum BooleanOperator
    {
    AND,
    OR
    }


    Examples:



    //"Toronto" sould be an invalid input when converting from JSON string array to c# long collection.
    {
    "PreferredNutTypes": [34,21],
    "GeographySearch": {
    "Operator": 1,
    "GeographyIDs": ["Toronto"]
    },
    }

    // This is what the model currently looks like in public HttpResponseMessage Squirrels(SquirrelsRequest model)
    new SquirrelsRequest()
    {
    PreferredNutTypes = new List<long>() { 34, 21 },
    GeographySearch = new GeographySearch()
    {
    Operator = 1
    GeographyIDs = new List<long>()
    }
    }


    Expectations:




  • Ideally catch any non-numeric values and return them as a bad request. Similar to how you can validate to how you use use data annotations to validate range.

  • Data annotation solution acceptable.

  • Ideally a clearer approach than accessing ModelState and parsing the error's message/key.

  • Ideally can be generically applied to any collection.


  • Things I've attempted:




  • Tried custom data annotation validator, but can only access the values after it's been parsed.

  • Tried accessing validation errors via HttpActionContext's ModelState but at best, I can only get these values...


  • System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.Message => "Error converting value "sonali7678687" to type 'System.Int64'. Path 'subjectSearch.writingAbout[0]', line 6, position 36."
    System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.InnerException.Message => "Input string was not in a correct format."


    ... surely there must be a better way of validating?



    UPDATE 1:
    Rephrased question to make explanation and intent more clear.










    share|improve this question
















    How can I validate and catch collection type conversion (JSON string array to C# long collection) for my System.Web.Http.ApiController class (before the model is initialized if possible)?



    I want to validate and catch any non-numeric elements in the JSON array to be return as a bad request response (maybe somehow with data annotation).



    When non-numeric JSON elements are included (to be converted to long collection), they fail to parse and get stripped before the model is passed to the ApiController method. Given the classes below, a valid input should contain only numeric values for "PerferredNutTypes" and "GeographyIDs".



    Classes



    public class SquirrelController : ApiController
    {
    [HttpPost]
    [Route("api/squirrels/search")]
    [SwaggerResponse(HttpStatusCode.OK, Type = typeof(SquirrelsResponse))]
    public HttpResponseMessage Squirrels(SquirrelsRequest model)
    {
    // model already parsed by the time breakpoint reaches here and non-convertable elements already stripped

    ...
    ...
    ...

    SquirrelsResponse results = Targeting.SearchForSquirrels(model);
    return Request.CreateResponse(HttpStatusCode.OK, results);
    }
    }

    public class SquirrelsRequest
    {
    public SquirrelsRequest() {}

    public List<long> PreferredNutTypes { get; set; } = new List<long>();
    public GeographySearch geographySearch { get; set; } = new GeographySearch();
    }

    public class GeographySearch
    {
    public GeographySearch() {}

    public BooleanOperator Operator { get; set; } = BooleanOperator.OR;
    public List<long> GeographyIDs { get; set; } = new List<long>();
    }

    public enum BooleanOperator
    {
    AND,
    OR
    }


    Examples:



    //"Toronto" sould be an invalid input when converting from JSON string array to c# long collection.
    {
    "PreferredNutTypes": [34,21],
    "GeographySearch": {
    "Operator": 1,
    "GeographyIDs": ["Toronto"]
    },
    }

    // This is what the model currently looks like in public HttpResponseMessage Squirrels(SquirrelsRequest model)
    new SquirrelsRequest()
    {
    PreferredNutTypes = new List<long>() { 34, 21 },
    GeographySearch = new GeographySearch()
    {
    Operator = 1
    GeographyIDs = new List<long>()
    }
    }


    Expectations:




  • Ideally catch any non-numeric values and return them as a bad request. Similar to how you can validate to how you use use data annotations to validate range.

  • Data annotation solution acceptable.

  • Ideally a clearer approach than accessing ModelState and parsing the error's message/key.

  • Ideally can be generically applied to any collection.


  • Things I've attempted:




  • Tried custom data annotation validator, but can only access the values after it's been parsed.

  • Tried accessing validation errors via HttpActionContext's ModelState but at best, I can only get these values...


  • System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.Message => "Error converting value "sonali7678687" to type 'System.Int64'. Path 'subjectSearch.writingAbout[0]', line 6, position 36."
    System.Web.Http.Controllers.HttpActionContext actionContext.ModelState.["model.GeographySearch.GeographyIDs[0]"].Errors[0].Exception.InnerException.Message => "Input string was not in a correct format."


    ... surely there must be a better way of validating?



    UPDATE 1:
    Rephrased question to make explanation and intent more clear.







    c# asp.net asp.net-mvc data-annotations asp.net-apicontroller






    share|improve this question















    share|improve this question













    share|improve this question




    share|improve this question








    edited Nov 20 '18 at 14:36







    setzuiro

















    asked Nov 19 '18 at 21:01









    setzuirosetzuiro

    167212




    167212








    • 1





      The ModelState errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value of GeographyIDs is invalid) so its not clear what you are expecting or want to do.

      – user3559349
      Nov 19 '18 at 22:15











    • I think you can get the current value from Request["GeographySearch.GeographyId"], but I would just look at ModelState.Where(m => m.Errors.Count > 0) and return a generic Response.StatusCode = 404 if the result is not null to keep it simple.

      – Kristianne Nerona
      Nov 20 '18 at 0:16
















    • 1





      The ModelState errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value of GeographyIDs is invalid) so its not clear what you are expecting or want to do.

      – user3559349
      Nov 19 '18 at 22:15











    • I think you can get the current value from Request["GeographySearch.GeographyId"], but I would just look at ModelState.Where(m => m.Errors.Count > 0) and return a generic Response.StatusCode = 404 if the result is not null to keep it simple.

      – Kristianne Nerona
      Nov 20 '18 at 0:16










    1




    1





    The ModelState errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value of GeographyIDs is invalid) so its not clear what you are expecting or want to do.

    – user3559349
    Nov 19 '18 at 22:15





    The ModelState errors are telling you want is invalid (i.e. in the example you gave, its telling you that the first value of GeographyIDs is invalid) so its not clear what you are expecting or want to do.

    – user3559349
    Nov 19 '18 at 22:15













    I think you can get the current value from Request["GeographySearch.GeographyId"], but I would just look at ModelState.Where(m => m.Errors.Count > 0) and return a generic Response.StatusCode = 404 if the result is not null to keep it simple.

    – Kristianne Nerona
    Nov 20 '18 at 0:16







    I think you can get the current value from Request["GeographySearch.GeographyId"], but I would just look at ModelState.Where(m => m.Errors.Count > 0) and return a generic Response.StatusCode = 404 if the result is not null to keep it simple.

    – Kristianne Nerona
    Nov 20 '18 at 0:16














    2 Answers
    2






    active

    oldest

    votes


















    0














    You can try JSON Schema validator, modify your method to receive JSON body, valid it first then convert it to model.



    public class SquirrelController : ApiController
    {
    [HttpPost]
    [Route("api/squirrels/search")]
    public SquirrelsResponse Squirrels(PostBody model)
    {
    var generator = new JSchemaGenerator();
    var schema = generator.Generate(typeof(SquirrelsRequest));
    var body = JObject.Parse(model.Body);

    bool valid = body.IsValid(schema, out IList<string> messages);
    if (!valid)
    {
    // Fail, do something
    }

    // Success
    }
    }

    public class PostBody
    {
    public string Body { get; set; }
    }


    Get more info...
    Validating JSON with JSON Schema
    Json.NET Schema






    share|improve this answer


























    • you can't validate it like that since messages will be empty if it's invalid

      – Marc
      Nov 20 '18 at 13:30











    • @Marc If you just accept request as a string like I said, not model, it would not invalid.

      – Died
      Nov 21 '18 at 5:45











    • Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs

      – Marc
      Nov 21 '18 at 13:07



















    -1














    Why is your type long? Also, are you going to be working with decimals? If not, what you need is int.TryParse(). Wherever you have int.parse (or long.parse() in your case) Replace it with int.TryParse(). TryParse returns a boolean (True or False) that will let you know if the string to be parsed was a number or not.



    example:



    bool isNumber = int.TryParse("Data I'm Trying to parse but it's a string", variableTheResultWillGetStoredToifSuccessful);


    This will come back false, and my super long variable name that you should never use is going to stay empty or rather unchanged. Therefore, you can do



    if(isNumber == false){
    //skip storing the number
    }else{
    //keep doing what you're doing;
    }


    You can also do, more concisely a rewrite of the above:



    if(isNumber){
    //keep doing what you're doing
    }


    More or less, that's the summary of it. TryParse will return a true or false based on if the parsing was successful or not without crashing your code, then you can use that information to continue how you seem fit.



    If you're going to be working with decimals use double instead of int.






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382558%2fhow-to-validate-type-of-collections%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      0














      You can try JSON Schema validator, modify your method to receive JSON body, valid it first then convert it to model.



      public class SquirrelController : ApiController
      {
      [HttpPost]
      [Route("api/squirrels/search")]
      public SquirrelsResponse Squirrels(PostBody model)
      {
      var generator = new JSchemaGenerator();
      var schema = generator.Generate(typeof(SquirrelsRequest));
      var body = JObject.Parse(model.Body);

      bool valid = body.IsValid(schema, out IList<string> messages);
      if (!valid)
      {
      // Fail, do something
      }

      // Success
      }
      }

      public class PostBody
      {
      public string Body { get; set; }
      }


      Get more info...
      Validating JSON with JSON Schema
      Json.NET Schema






      share|improve this answer


























      • you can't validate it like that since messages will be empty if it's invalid

        – Marc
        Nov 20 '18 at 13:30











      • @Marc If you just accept request as a string like I said, not model, it would not invalid.

        – Died
        Nov 21 '18 at 5:45











      • Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs

        – Marc
        Nov 21 '18 at 13:07
















      0














      You can try JSON Schema validator, modify your method to receive JSON body, valid it first then convert it to model.



      public class SquirrelController : ApiController
      {
      [HttpPost]
      [Route("api/squirrels/search")]
      public SquirrelsResponse Squirrels(PostBody model)
      {
      var generator = new JSchemaGenerator();
      var schema = generator.Generate(typeof(SquirrelsRequest));
      var body = JObject.Parse(model.Body);

      bool valid = body.IsValid(schema, out IList<string> messages);
      if (!valid)
      {
      // Fail, do something
      }

      // Success
      }
      }

      public class PostBody
      {
      public string Body { get; set; }
      }


      Get more info...
      Validating JSON with JSON Schema
      Json.NET Schema






      share|improve this answer


























      • you can't validate it like that since messages will be empty if it's invalid

        – Marc
        Nov 20 '18 at 13:30











      • @Marc If you just accept request as a string like I said, not model, it would not invalid.

        – Died
        Nov 21 '18 at 5:45











      • Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs

        – Marc
        Nov 21 '18 at 13:07














      0












      0








      0







      You can try JSON Schema validator, modify your method to receive JSON body, valid it first then convert it to model.



      public class SquirrelController : ApiController
      {
      [HttpPost]
      [Route("api/squirrels/search")]
      public SquirrelsResponse Squirrels(PostBody model)
      {
      var generator = new JSchemaGenerator();
      var schema = generator.Generate(typeof(SquirrelsRequest));
      var body = JObject.Parse(model.Body);

      bool valid = body.IsValid(schema, out IList<string> messages);
      if (!valid)
      {
      // Fail, do something
      }

      // Success
      }
      }

      public class PostBody
      {
      public string Body { get; set; }
      }


      Get more info...
      Validating JSON with JSON Schema
      Json.NET Schema






      share|improve this answer















      You can try JSON Schema validator, modify your method to receive JSON body, valid it first then convert it to model.



      public class SquirrelController : ApiController
      {
      [HttpPost]
      [Route("api/squirrels/search")]
      public SquirrelsResponse Squirrels(PostBody model)
      {
      var generator = new JSchemaGenerator();
      var schema = generator.Generate(typeof(SquirrelsRequest));
      var body = JObject.Parse(model.Body);

      bool valid = body.IsValid(schema, out IList<string> messages);
      if (!valid)
      {
      // Fail, do something
      }

      // Success
      }
      }

      public class PostBody
      {
      public string Body { get; set; }
      }


      Get more info...
      Validating JSON with JSON Schema
      Json.NET Schema







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Dec 10 '18 at 2:05









      MonLiH

      8110




      8110










      answered Nov 20 '18 at 8:30









      DiedDied

      12




      12













      • you can't validate it like that since messages will be empty if it's invalid

        – Marc
        Nov 20 '18 at 13:30











      • @Marc If you just accept request as a string like I said, not model, it would not invalid.

        – Died
        Nov 21 '18 at 5:45











      • Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs

        – Marc
        Nov 21 '18 at 13:07



















      • you can't validate it like that since messages will be empty if it's invalid

        – Marc
        Nov 20 '18 at 13:30











      • @Marc If you just accept request as a string like I said, not model, it would not invalid.

        – Died
        Nov 21 '18 at 5:45











      • Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs

        – Marc
        Nov 21 '18 at 13:07

















      you can't validate it like that since messages will be empty if it's invalid

      – Marc
      Nov 20 '18 at 13:30





      you can't validate it like that since messages will be empty if it's invalid

      – Marc
      Nov 20 '18 at 13:30













      @Marc If you just accept request as a string like I said, not model, it would not invalid.

      – Died
      Nov 21 '18 at 5:45





      @Marc If you just accept request as a string like I said, not model, it would not invalid.

      – Died
      Nov 21 '18 at 5:45













      Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs

      – Marc
      Nov 21 '18 at 13:07





      Sorry I missed that part but then he changes the api. It would be confusing for the customer to see a string instead of a list of longs

      – Marc
      Nov 21 '18 at 13:07













      -1














      Why is your type long? Also, are you going to be working with decimals? If not, what you need is int.TryParse(). Wherever you have int.parse (or long.parse() in your case) Replace it with int.TryParse(). TryParse returns a boolean (True or False) that will let you know if the string to be parsed was a number or not.



      example:



      bool isNumber = int.TryParse("Data I'm Trying to parse but it's a string", variableTheResultWillGetStoredToifSuccessful);


      This will come back false, and my super long variable name that you should never use is going to stay empty or rather unchanged. Therefore, you can do



      if(isNumber == false){
      //skip storing the number
      }else{
      //keep doing what you're doing;
      }


      You can also do, more concisely a rewrite of the above:



      if(isNumber){
      //keep doing what you're doing
      }


      More or less, that's the summary of it. TryParse will return a true or false based on if the parsing was successful or not without crashing your code, then you can use that information to continue how you seem fit.



      If you're going to be working with decimals use double instead of int.






      share|improve this answer




























        -1














        Why is your type long? Also, are you going to be working with decimals? If not, what you need is int.TryParse(). Wherever you have int.parse (or long.parse() in your case) Replace it with int.TryParse(). TryParse returns a boolean (True or False) that will let you know if the string to be parsed was a number or not.



        example:



        bool isNumber = int.TryParse("Data I'm Trying to parse but it's a string", variableTheResultWillGetStoredToifSuccessful);


        This will come back false, and my super long variable name that you should never use is going to stay empty or rather unchanged. Therefore, you can do



        if(isNumber == false){
        //skip storing the number
        }else{
        //keep doing what you're doing;
        }


        You can also do, more concisely a rewrite of the above:



        if(isNumber){
        //keep doing what you're doing
        }


        More or less, that's the summary of it. TryParse will return a true or false based on if the parsing was successful or not without crashing your code, then you can use that information to continue how you seem fit.



        If you're going to be working with decimals use double instead of int.






        share|improve this answer


























          -1












          -1








          -1







          Why is your type long? Also, are you going to be working with decimals? If not, what you need is int.TryParse(). Wherever you have int.parse (or long.parse() in your case) Replace it with int.TryParse(). TryParse returns a boolean (True or False) that will let you know if the string to be parsed was a number or not.



          example:



          bool isNumber = int.TryParse("Data I'm Trying to parse but it's a string", variableTheResultWillGetStoredToifSuccessful);


          This will come back false, and my super long variable name that you should never use is going to stay empty or rather unchanged. Therefore, you can do



          if(isNumber == false){
          //skip storing the number
          }else{
          //keep doing what you're doing;
          }


          You can also do, more concisely a rewrite of the above:



          if(isNumber){
          //keep doing what you're doing
          }


          More or less, that's the summary of it. TryParse will return a true or false based on if the parsing was successful or not without crashing your code, then you can use that information to continue how you seem fit.



          If you're going to be working with decimals use double instead of int.






          share|improve this answer













          Why is your type long? Also, are you going to be working with decimals? If not, what you need is int.TryParse(). Wherever you have int.parse (or long.parse() in your case) Replace it with int.TryParse(). TryParse returns a boolean (True or False) that will let you know if the string to be parsed was a number or not.



          example:



          bool isNumber = int.TryParse("Data I'm Trying to parse but it's a string", variableTheResultWillGetStoredToifSuccessful);


          This will come back false, and my super long variable name that you should never use is going to stay empty or rather unchanged. Therefore, you can do



          if(isNumber == false){
          //skip storing the number
          }else{
          //keep doing what you're doing;
          }


          You can also do, more concisely a rewrite of the above:



          if(isNumber){
          //keep doing what you're doing
          }


          More or less, that's the summary of it. TryParse will return a true or false based on if the parsing was successful or not without crashing your code, then you can use that information to continue how you seem fit.



          If you're going to be working with decimals use double instead of int.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 19 '18 at 21:42









          The.NetDeveloperThe.NetDeveloper

          13




          13






























              draft saved

              draft discarded




















































              Thanks for contributing an answer to Stack Overflow!


              • Please be sure to answer the question. Provide details and share your research!

              But avoid



              • Asking for help, clarification, or responding to other answers.

              • Making statements based on opinion; back them up with references or personal experience.


              To learn more, see our tips on writing great answers.




              draft saved


              draft discarded














              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53382558%2fhow-to-validate-type-of-collections%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown





















































              Required, but never shown














              Required, but never shown












              Required, but never shown







              Required, but never shown

































              Required, but never shown














              Required, but never shown












              Required, but never shown







              Required, but never shown







              Popular posts from this blog

              Guess what letter conforming each word

              Port of Spain

              Run scheduled task as local user group (not BUILTIN)