Home > other >  Validating url string by using whitelist objects
Validating url string by using whitelist objects

Time:09-17

I am trying to validate a URL link, by checking against valid parameters and acceptable values (whitelist) using an object.

const validParams = {
   "brand",
   "item",
   "size",
   "country"
}

const validBrandValues = {
   "nike",
   "adidas",
   "puma",
   ...
}

export const Validate = (link) => {
    const urltest = "https://example.com/?brand=nike adidas puma cat&item=trainers jackets socks&random=hello"
    var url = "";
    try {
        url = decodeURI(urltest);
      } catch (e) { 
        console.error(e);
    }
    const params = url.split("?");
    const value = params[1].split("&").map(item => item.split("="));

    console.log(value)
    //for(int i = 0; i < value.length; i  ){
       //if(value[i] === "brand"){
          //for(int j = 0; j < value[i].length; j  ){
             //validBrandValue.contains()
          //}
       //}
    //}
}
//Current Output
(3) [Array(2), Array(2), Array(2)]
0: (2) ["brand", "nike adidas puma cat"]
1: (2) ["item", "trainers jackets socks"]
2: (2) ["random", "hello"]

How can I efficiently analyze the input URL in the Validate function to flag any non-whitelisted values or parameters. In the provided link example it will flag that cat is an unknown brand and random parameter is not valid

CodePudding user response:

Here is one way:

const validValues = { 
  brand: [ "nike", "adidas", "puma" ],
  item:  [ "trainers", "jackets", "socks"]
}

const Validate = link => {
  const url = new URL(link);
  const entries = [...url.searchParams.entries()];
  let testArr = entries.map(entry => {
    const key = entry[0];
    const valids = validValues[key]; // key exists
    const values = entry[1].split(" "); // parms space separated
    return {
      [key]: valids ? values.map(elem => ({ [elem]:valids.includes(elem)})) : false
    }
  })
  return testArr;
};
console.log(Validate("https://example.com/?brand=nike adidas puma cat&item=trainers jackets socks&random=hello"))

  • Related