Welcome to my dynamic form validation tutorial using object evaluator.
Note: this tutorial is not for RegExp but to help you understand the best use case of “[ ]” to access object properties.
Quick information: there are two possible ways to access an object which includes:
objName.objProperty
objName[objProperty]
But the question here is what is the best use case?
The answer is: use the "dot" syntax when you want to access a property directly(that is static) and use the square bracket when you want to access a property dynamically. Dynamically means the property to be accessed changes as the user changes the value. E.g:
const STAFF_NAMES ={
staffOne:”CreativeAdams”,
staffTwo:”CreativePerete”,
staffThree:”CreativeJerry”
}
const getStaffName=staffKey=>{
return STAFF_NAMES[staffKey]
}
Below example is simply one of the dynamic ways to access properties
getStaffName(“staffOne”);//CreativeAdams
getStaffName(“staffTwo”);//CreativePerete
Link to the complete code on how to dynamically validate your form using RegExp and object evaluator syntax.
Click Me
Quick note: the form validation could be performed in many ways e.g:
By validating each of the inputs which is a pain to developers.
By Looping through the inputs element and accessing their type or name, then deciding on the validation. But I bet you, that will cause a time-complexity issue.
The best solution is provided here by me: Click Me
Quick Explanation
The most important thing inside the code is at line 13, that’s where the evaluation and validation happens.
So this RegExp[e.target.name] is what enables the dynamism. This is a javascript syntax for object/variable evaluation. Also, if you are from React community you definitely have come across dynamic input value-handling to state by simply doing this:
this.setState({…this.state,
///So this is simply same thing(evaluation).
Thanks and have a wonderful day.
Top comments (0)