Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Write Typescript Function to Validate Inputs of JSON File

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 523
    Answer it

    I am in need of a method written in typescript to validate the inputs of a JSON file. 



    Need help in writing method(function) to analyze the contents of the JSON and make sure that it is internally consistent
     

    For ex: Content of the data.json is as follows

    "configuration": {
        "log_servers": [
            {
                "transport": "UDP",
                "ip": "10.44.34.254",
                "policy_url": "http://testurl.com"
            }
        ]
    }

    I need to validate the contents of the above json file for the values.

    • Part 1:

    If the value either the values from the below enum (i.e., 'UDP' or 'TCP'), the method should return 'valid', otherwise 'invalid' output.

    enum logTransports {
    UDP = "UDP",
    TCP = "TCP"
    }

    So,

    "transport": "UDP" --> is valid
    "transport": "TCP" --> is valid
    "transport": "HTTP" --> is invalid
    "transport": "XYZ" --> invalid
    • Part 2:

    Validate the input "ip" is correct.

    "ip": "10.44.34.254" --> is valid
    "ip": "300.76.34.254" --> is invalid (300 is invalid value)
    "ip": "10.44.xx.ooo" --> is invalid (string not allowed to be part of IP value)
    • Part 3:

    Validate the input of "policy_url" is correct.

    "policy_url": "http://testurl.com" --> is valid
    "policy_url": "https://testurl.com" --> is valid
    "policy_url" : "utrs://xya.com" --> is invalid (utrs is invalid value - 
    only https or http)
    "policy_url": "https:/testurl.com" --> is invalid (regex [a-z]://[a-z] is not matching)
    "policy_url": "https//testurl.com" --> is invalid (regex [a-z]://[a-z] is not matching)

    Expected:

    The method(function) should return a tuple with an indication of success or failure as one item and a description of the problem found.

    ex:

    ["transport", failure, "Wrong protocol"]
    ["ip", failure, "String used in values"]
    ["url", success, "URL is valid"]

    My urgent need is about "Part 1". I am new to typescript, I haven't tried anything similar yet.

    A design that would to extend on the 'rules' used for validation would be welcome. That would be to include other requirements like type checking of inputs etc.

    Any ideas to implement are most welcome. Thanks for your help.

 0 Answer(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: