Design a form component which takes input from its user and displays a form
Design: Here are the things that it should support:
- Grouping of the fields of the form
- Validations for fields
- Submit button
For example, the user might want to validate if the input is a valid address and might want this component to have default validations for email, etc.
Let’s try to create a very basic data model for our component.
For our minimalistic implementation, we might want to use these fields.
- Id: The id for the field
- Type: text/dropdown etc
- Subtype: For input type text we might want password etc
- Values: for dropdown/Radio
- Validator: the custom validator provided by the user. We can use the value of “email” etc to provide default validation.
- Group: the group to which this field should belong
- Placeholder: placeholder if needed for the field.
- Handler: to provide a callback/option for the submit button click
For this, we would try to use the MVC pattern in JS. First, let’s develop our model class.
For our minimalistic implementation, we will keep the input for this component in our model class.
Our model will have input for the component which will be hardcoded now and an event that will notify that our input has changed.
Here is the minimalistic implementation
Here the event class is basic pub/sub implementation where each module can react to an event. Here is the event class
Now coming to our controller. For our sample use case, we have triggered items added to the model on controller initialization only.
Below is the class:
Now coming to our main class which will eventually render the form which is our view class.
Here is the view class:
Here we store the model(which in our case is the input to this component) and the validators for each field.
Also, we attach the event handler to our model change which will create the view. Here is the complete code
Here is how we instantiate the component