In the Open Event Frontend, users can create ‘Access codes’ for an event. Creation of access codes has a form located at the ‘tickets/access-codes/create’ which contains multiple form inputs such as ‘Number of Access tickets’, ‘status’, ‘Minimum tickets’, ‘Maximum tickets’, etc. To create an access code, a user has to fill the form. The form is validated at the time of submission. However, it should not happen that sometimes a user fills minimum number of tickets greater than maximum number of tickets. Semantic UI provides inbuilt validation for many inputs like the ‘text’, ‘email’, ‘password’, ‘number’ etc. But in some cases, it may happen that we need custom validation for some inputs before submitting the form.
Number of tickets
Min and max tickets
As shown in the above screenshot, the access code form has some inputs like ‘Min’, ‘Max’, ‘Number of access tickets’, etc. Here we need to ensure that the minimum number of tickets should not exceed the maximum number of tickets, also, the maximum number should not be greater than the total tickets, etc. To achieve this, we need to use the custom validation provided by Semantic UI.
To create a custom validation, we need to have a custom rule for it. To ensure the minimum value does not exceed the maximum value of the ticket, we first set up a rule for validation as follows:
In the above snippet, we introduced a new rule in the ‘min’ validation set of rules. The new rule called ‘checkMaxMin’ has to be defined so that it checks the necessary condition and returns the value desired.
Above code shows the rule which we defined in to check the required condition. It retrieves the data from the form by ‘this.get’ method and then checks whether the maximum tickets exceed the minimum. If they do, the function returns false, else it returns true. In this way, when a true value is returned, the form accepts the inputs else it rejects. The following screenshots illustrate the same:
In the same way, we can write custom validation for checking whether maximum tickets exceed the total number of tickets. Following is the code snippet and screenshot for the same.
Thus, in this way, we can use custom validation for some form inputs when we want to customise the inputs based on our requirements.
- Semantic UI forms: https://semantic-ui.com/behaviors/form.html
- Source code: https://github.com/fossasia/open-event-frontend/blob/development/app/components/forms/events/view/create-access-code.js
- Pen on codepen: https://codepen.io/appsoa/pen/BoxQeL