In Trivule, rules govern how form fields are validated. You might find that the existing rules don't quite fit your needs or that you need to introduce custom rules. Here's a quick guide on how to add or modify rules in Trivule
Step 1: Accessing the rule
Method
To add or modify a rule, you'll use the rule
method of the TrBag
class. This method allows you to define the behavior of a rule according to your requirements.
Step 2: Writing the Rule Callback
The heart of defining a rule lies in the rule callback function. This function takes in the value of the field to be validated and returns an object indicating whether the validation passes or fails. You can customize the validation logic within this callback.
Step 3: Defining the Rule Parameters
const notSudoRule = (input,param,type) => {
return {
value: input,
passes: input != "sudo",
type: "text", // Optional
alias: undefined, // Optional
};
};
When defining a rule, you'll provide several parameters:
- Rule Name: Assign a name to your rule.
- Callback Function: Define the callback function that implements the validation logic.
- Message: Optionally, provide a message to be displayed when the rule fails.
- Locale: If needed, specify the language for error messages.
Step 4: Example Usage
Let's consider an example where we want to create a rule called notSudo
, which ensures that the input value is not equal to "sudo". We define the rule callback function accordingly and use the TrBag.rule
method to add the rule to Trivule.
const notSudoRule = (input,param,type) => {
return {
value: input,
passes: input != "sudo",
type: "text", // Optional
alias: undefined, // Optional
};
};
TrBag.rule(
"notSudo",
notSudoRule,
"The input value should not be 'sudo'",
"en"
);
Step 5: Testing Your Rule
Once you've added your custom rule, you can immediately start using it in your forms. Test the rule to ensure it behaves as expected and meets your validation requirements.
Conclusion
By following these steps, you can easily add or modify rules in Trivule to tailor form validation to your specific needs. Experiment with different validation logic and parameters to create robust and effective validation rules for your applications.
That's it! You've successfully learned how to add or modify rules in Trivule. Happy coding!
Top comments (0)