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:
example.widgets[0].name, widgets[0] is still a valid string when .split()"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.
string.split will never throw an exception when passed a string. Therefore, via these rules, any string is valid dot notation. In that case you only need to verify whether something is a string, which you can do like so:
typeof content === 'string'
You're missing something. Your original code won't work with the input:
content1 = "example.widgets[.0].name"
content2 = "example.widgets[0].name."