I'm building out a component that accepts an input of dot notation. I want to validate the input and when I stopped to think about "what is valid dot notation" I figured this would be a simple way of doing it, but it almost seems too simple so now I'm wondering if I'm missing something:
function isValidDotNotation(content: string) {
try {
content.split(".")
return true
} catch (exception) {
return false
}
}
So:
- dot notation is a way of specifying a namespace within a json data structure then it seems like our main concern is validating keys
- JSON requires strings for keys
- the split static method hangs off of String so you'd only be able to fire it on a string
- Specifying an array index in dot notation just makes the square brackets part of a string (e.g. in
example.widgets[0].name,widgets[0]is still a valid string when.split() - A single level dot notation string can still be split into a single array value (e.g.
"test".split(".")still works)
So when we fire split, as long as we don't throw an exception the the string given should be a valid dot notation. It may or may not lead you to anything within the json structure, but as far as a valid value it should be good, right?
Am I missing any nuance here? I've seen examples of people looping through the structure and stuff, but it seems like overkill to validate unless I'm missing something.
You're missing something. Your original code won't work with the input: