diff --git a/README.md b/README.md index 630baac..29b6a3e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# Website +# Trivule documentation -This website is built using [Docusaurus 3](https://docusaurus.io/), a modern static website generator. +This repository contains the official documentation for Trivule ### Installation @@ -21,21 +21,3 @@ This command starts a local development server and opens up a browser window. Mo ``` $ npm build ``` - -This command generates static content into the `build` directory and can be served using any static contents hosting service. - -### Deployment - -Using SSH: - -``` -$ USE_SSH=true npm deploy -``` - -Not using SSH: - -``` -$ GIT_USER= npm deploy -``` - -If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. diff --git a/docs/events/index.md b/docs/events/index.md index e8844c8..16ba35d 100644 --- a/docs/events/index.md +++ b/docs/events/index.md @@ -10,7 +10,7 @@ Trivule provides the ability to listen for different JavaScript events to trigge ## Triggering Validation with Default Events -By default, Trivule uses the `input`, `blur`, and `change` events to trigger form field validation. This means that whenever a user enters, leaves, or modifies a value in a form field, validation is automatically triggered. +By default, Trivule uses the `blur`, and `change` events to trigger form field validation. This means that whenever a user enters, leaves, or modifies a value in a form field, validation is automatically triggered. For instance, if you want to trigger validation when an element is hovered over by the mouse cursor, you can use Trivule's `data-tr-events` attribute and specify the `mouseenter` event as follows: diff --git a/docs/form-validation.md b/docs/form-validation.md new file mode 100644 index 0000000..04ed208 --- /dev/null +++ b/docs/form-validation.md @@ -0,0 +1,563 @@ +--- +sidebar_position: 4 +title: Form Validation +--- + +# Form Validation + +## Global Validation + +If you have a website or application and want to apply the same validation rules to all forms without managing each form individually, you can use global validation with [declarative validation](#). + +## Usage + +To set up global validation, simply initialize Trivule: + +```html + +``` + +This activates global validation for all your forms. +Form validation involves validating a set of HTML fields, whether inside a `
` element or grouped within a container such as a `
`. + +## TrivuleForm + +TrivuleForm offers two validation approaches: declarative and imperative, to address different form validation needs. + +### Declarative Validation + +Declarative validation allows validating a form by simply specifying validation rules in the attributes of HTML fields. It's a simple and convenient approach for basic form validation. + +Example usage: + +```html + +
+ + +
+
+
+ + +
+
+

+ +

+ +``` + +Validation initialization: + +```js +const trForm = new TrivuleForm("form"); +``` + +With this declarative approach, the form is automatically validated without writing additional JavaScript code, which is ideal for simple form validation needs. + +### Imperative Validation + +Imperative validation allows defining validation rules and applying them dynamically using JavaScript code. This provides greater flexibility for more complex form validation cases. + +Example usage: + +```js +const trivuleForm = new TrivuleForm("form",{ + realTime:false, + feedbackSelector:".invalid-feedback" +}); +// Define imperative validation rules for each form field +trivuleForm.make([ + { + selector: "email", + rules: ["required", "email", "maxlength:32"], + }, + { + selector: "message", + rules: ["required", "between:2,250", "endWith:."], + }, +]); +``` + +With this imperative approach, you can dynamically define validation rules and interact more actively with the form according to specific needs. + + ### Validation Settings + +- To initialize form validation, the first argument passed to the constructor is a CSS selector. It can be a standard `
` element or a `
` container containing a set of inputs to validate. +- The second parameter consists of a basic configuration to customize the validation behavior. + +Here's an explanation of each available option: + +- `auto` (optional): This option specifies whether the form should be validated as the user types in the form fields. By default, this option is disabled (`false`). + +- `local` (optional): This option allows you to set the language for validation error messages. You can specify the language as a string. For example, `"fr"` for French. This option is also optional. + +- `validClass` (optional): This is the CSS class that will be added to all the inputs in the form when they are valid. If this option is not set, no class will be added. + +- `invalidClass` (optional): This is the CSS class that will be added to all the inputs in the form when they are invalid. If this option is not set, `is-invalid` class will be added. + +Here's the translation: + +- `feedbackSelector` (optional): If this option is not specified, Trivule will first check if a selector is indicated during declaration with the `make` method, and then use that selector. In the absence of a selector, Trivule will check if the input has an associated HTML element with the `data-tr-feedback` attribute set to the input's name. If no element is found in either of these cases, no feedback message will be displayed. + +- `realTime` (optional): This option specifies whether validation should be performed in real-time as the user types in the form fields. By default, this option is disabled (`false`). + +These options allow you to customize the validation of your form according to your specific needs. +**Default values** +```js +const options = { + auto: true, + local: { + lang: "en", + }; + validClass: "", + invalidClass: "is-invalid", + feedbackSelector: "[data-tr-feedback={name}]", //where {name} we be replaced with the input name + realTime: true; +}; +``` +### Make Validation + +The `make` method in the `TrivuleForm` class is used to define and apply validation rules to form inputs. This method allows you to specify validation parameters for multiple inputs, either by passing an array of input parameters or an object containing input names and their corresponding parameters. + +#### Usage + +The `make` method can be used in two ways: +1. By passing an array of [input parameters](#). +2. By passing an object with input names as keys and their [parameters](#) as values. + +#### Example 1: Using an Array of Input Parameters +In this example, we define validation rules for two inputs using an array of input parameters. + +```typescript +const trivuleForm = new TrivuleForm("form"); + +// Define validation rules for each form field +trivuleForm.make([ + { + selector: "age", // The input name + rules: "required|between:18,40", + }, + { + selector: "#birthDayInput", + rules: "required|date", + }, +]); +``` +#### Example 2: Using an object with input names and parameters + +In this example, we define validation rules for multiple inputs using an object where keys are input names and values are their corresponding parameters. + +```typescript +const trivuleForm = new TrivuleForm("form"); + +const inputs = { + age: { + rules: "required|between:18,40", + }, + birthDay: { + rules: "required|date", + selector: "#birthDayInput", + }, + message: { + rules: "required|only:string", + }, +}; + +// Apply validation rules +trivuleForm.make(inputs); +``` + +#### Example 3: Chaining `make` Method Calls + +You can also chain multiple `make` method calls to define validation rules for different sets of inputs. + +```typescript +const trivuleForm = new TrivuleForm("form"); + +trivuleForm + .make([ + { + selector: "age", + rules: "required|between:18,40", + }, + { + selector:"birthDayInput", + rules: "required|date", + }, + ]) + .make({ + message: { + rules: "required|only:string", + }, + }); +``` + + +### Handling Failed Validation + +The `TrivuleForm` class offers two approaches for handling failed validation: + +**1. Using `onFails` Method:** + +* Conveniently attaches an event listener to the `"tr.form.fails"` event. +* Event triggers upon form validation failure. +* Provides a callback function with the `TrivuleForm` instance, enabling access to validation-related information. + +**Example:** + +```typescript +const trivuleForm = new TrivuleForm("form"); + +trivuleForm.onFails((trivuleForm) => { + console.log("Form validation failed!", trivuleForm); + // Additional error handling logic... +}); +``` + +**2. Direct Event Listener:** + +* Listen for the `"tr.form.fails"` event directly on the form element. +* Offers more control over event handling. +* Useful when avoiding dependency on `TrivuleForm` methods or for custom event handling needs. + +**Example:** + +```typescript +const formElement = document.getElementById("form"); + +formElement.addEventListener("tr.form.fails", (event) => { + console.log("Form validation failed!", event.target); // Target is the form element + // Additional error handling logic... +}); +``` + +**Choosing the Approach:** + +* **`onFails` Method:** Cleaner and encapsulated when working within the `TrivuleForm` class context. +* **Direct Event Listener:** Offers more control and independence from `TrivuleForm` methods. + + +### Handling Successful Validation + +Similarly to handling failed validation, you can manage successful validation using the `onPasses` method or by directly listening for the `"tr.form.passes"` event. + +**1. Using `onPasses` Method:** + +* Attach an event listener to the `"tr.form.passes"` event. +* Executed when the form validation succeeds. +* Provides a callback function with the `TrivuleForm` instance, enabling specific actions upon successful validation. + +**Example:** + +```typescript +const trivuleForm = new TrivuleForm("form"); + +trivuleForm.onPasses((trivuleForm) => { + console.log("Form validation passed!", trivuleForm); + // Additional actions upon successful validation... +}); +``` + +**2. Direct Event Listener:** + +* Listen for the `"tr.form.passes"` event directly on the form element. +* Offers more control over event handling and independence from `TrivuleForm` methods. + +**Example:** + +```typescript +const formElement = document.getElementById("form"); + +formElement.addEventListener("tr.form.passes", (event) => { + console.log("Form validation passed!", event.target); // Target is the form element + // Additional actions upon successful validation... +}); +``` + +**Choosing the Approach:** + +* **`onPasses` Method:** Convenient and encapsulated within the `TrivuleForm` class context. +* **Direct Event Listener:** Provides more flexibility and control over event handling. + + +### Attaching Event Listeners + +The `on` method in the `TrivuleForm` class allows you to attach event listeners to the container element of the form. + +#### Syntax + +```typescript +trivuleForm.on(eventName: string, callback: EventCallback): void; +``` + +#### Parameters + +- `eventName`: A string representing the name of the event to listen to. +- `callback`: The callback function to execute when the specified event occurs. This function takes an event of type `Event` as a parameter and returns nothing. + +#### Example + +```typescript +// Attach an event listener to handle form initialization +trivuleForm.on("tr.form.init", (event) => { + console.log("Form initialized", event.detail); + // Additional actions to perform when the form is initialized +}); + + +trivuleForm.on("click", (event) => { + //form click event +}); +``` + +#### Usage + +You can use the `on` method to listen for various events related to the form, such as form initialization, validation, submission, and more. Simply provide the appropriate event name and the corresponding callback function to handle the event. + +### Emitting Custom Events + +The `emit` method in the `TrivuleForm` class enables you to emit custom events from the container element of the form. + +#### Syntax + +```typescript +trivuleForm.emit(eventName: string, data?: any): void; +``` + +#### Parameters + +- `eventName`: A string representing the name of the custom event to emit. +- `data` (optional): Additional data to pass along with the event. + +#### Example + +```typescript +// Emit a custom event to indicate form validation +trivuleForm.emit("tr.form.validate", { + valid: true, + message: "Form validation completed successfully", +}); +``` + +#### Usage + +You can use the `emit` method to trigger custom events at specific points within your form's lifecycle or in response to certain actions. These events can be listened to and handled elsewhere in your application logic. By emitting custom events, you can create a more modular and flexible architecture for managing form behavior and interactions. + +### Handling Form Updates and Validation Events + +The `onUpdate` and `onValidate` methods in the `TrivuleForm` class provide powerful event handling capabilities for managing form updates and validation processes. + +#### `onUpdate` Method + +The `onUpdate` method allows you to attach event listeners that respond to updates in the form inputs. When any input value within the form is updated, the provided callback function is executed. + +##### Syntax + +```typescript +trivuleForm.onUpdate(callback: TrivuleFormHandler): void; +``` + +##### Parameters + +- `callback`: A callback function to execute when any input value in the form is updated. This function takes the form instance as a parameter. + +##### Example + +```typescript +trivuleForm.onUpdate((form) => { + console.log("Form updated", form); +}); +``` + +#### `onValidate` Method + +The `onValidate` method allows you to attach event listeners that respond to the validation process of the form. When the form is validated, either manually or automatically, the provided callback function is executed. + +##### Syntax + +```typescript +trivuleForm.onValidate(callback: TrivuleFormHandler): void; +``` + +##### Parameters + +- `callback`: A callback function to execute when the form is validated. This function takes the form instance as a parameter. + +##### Example + +```typescript +trivuleForm.onValidate((form) => { + console.log("Form validated", form); +}); +``` + +#### Usage + +You can use the `onUpdate` method to perform actions whenever any input value in the form is updated. This is useful for dynamically responding to changes in form data. + +Similarly, the `onValidate` method allows you to execute custom logic when the form undergoes validation. You can use this to handle validation outcomes, update UI elements, or trigger additional processes based on the validation result. + +### Iterating Through Form Inputs with the `each` Method + +The `each` method in the `TrivuleForm` class facilitates the iteration through all inputs within the form. This method allows you to perform actions or apply logic to each input individually. + +### Iterates through each input + +The `each` method iterates through each input within the form and executes a callback function for each input. + +##### Syntax + +```typescript +each(callback: ITrivuleInputCallback): void; +``` + +##### Parameters + +- `callback`: A callback function that takes a `TrivuleInput` instance as its parameter. This function will be executed for each input within the form. + +##### Example + +```typescript +trivuleForm.each((input) => { + console.log("Input name:", input.getName()); + console.log("Input value:", input.getValue()); + console.log("Input validation status:", input.passes()); +}); +``` + +#### Usage + +The `each` method is useful when you need to perform operations on each input within the form individually. For example, you can use it to access the name, value, or validation status of each input, apply specific styling or behavior, or trigger custom actions based on input properties. + +In this example, we iterate through each input within the `trivuleForm` instance and log their name, value, and validation status. You can replace the callback function with your custom logic to suit your specific requirements, such as updating UI elements, performing calculations, or triggering events based on input properties. + + + +### Managing Inputs in TrivuleForm + +In the `TrivuleForm` class, you can interact with individual form inputs through various methods. These methods allow you to retrieve information about inputs, such as their validation status or values. + +#### `inputs` Method + +The `inputs` method retrieves an array of all inputs within the form. You can specify whether you want strict or non-strict output. In strict mode, you get objects containing only the input name, value, while in non-strict mode, you receive instances of `TrivuleInput`. + +##### Syntax + +```typescript +inputs(strict?: boolean): ITrivuleInputObject[] | TrivuleInput[]; +``` + +##### Parameters + +- `strict`: (Optional) A boolean indicating whether to return strict output (default is `true`). + +##### Returns + +An array of inputs based on the specified mode. + +##### Example + +```typescript +// Get all inputs in strict mode +const strictInputs = trivuleForm.inputs(); //return name, value object + +// Get all inputs in non-strict mode +const nonStrictInputs = trivuleForm.inputs(false); //Return instances of `TrivuleInput` +``` + +#### `validated` Method + +The `validated` method retrieves an array of inputs that have passed validation. Similar to the `inputs` method, you can specify whether to return strict or non-strict output. + +##### Syntax + +```typescript +validated(strict?: boolean): ITrivuleInputObject[] | TrivuleInput[]; +``` + +##### Parameters + +- `strict`: (Optional) A boolean indicating whether to return strict output (default is `true`). + +##### Returns + +An array of validated inputs based on the specified mode. + +##### Example + +```typescript +// Get validated inputs in strict mode +const validatedInputs = trivuleForm.validated(); + +// Get validated inputs in non-strict mode +const nonStrictValidatedInputs = trivuleForm.validated(false); +``` + +#### `failed` Method + +The `failed` method retrieves an array of inputs that have failed validation. Like the previous methods, you can choose between strict and non-strict output. + +##### Syntax + +```typescript +failed(strict?: boolean): ITrivuleInputObject[] | TrivuleInput[]; +``` + +##### Parameters + +- `strict`: (Optional) A boolean indicating whether to return strict output (default is `true`). + +##### Returns + +An array of failed inputs based on the specified mode. + +##### Example + +```typescript +// Get failed inputs in strict mode +const failedInputs = trivuleForm.failed(); + +// Get failed inputs in non-strict mode +const nonStrictFailedInputs = trivuleForm.failed(false); +``` + +These methods provide convenient ways to access and manage inputs within the TrivuleForm instance, allowing you to handle validation results effectively and tailor your application's behavior accordingly. + + +### Validation status + +#### Description +The `isValid()` method determines whether the entire form is currently valid. + +#### Syntax +```typescript +isValid(): boolean +``` + +#### Returns +- A boolean value indicating whether all inputs in the form are currently passing validation. + - `true`: All inputs are valid. + - `false`: At least one input is invalid. + +#### Example +```typescript +// Check if the form is valid +const isFormValid = trivuleForm.isValid(); +if (isFormValid) { + console.log("The form is valid."); +} else { + console.log("The form contains invalid inputs."); +} +``` +You can also you the `passes()` method or the `valid` property + diff --git a/docs/index.md b/docs/index.md index cb3656d..06b485e 100644 --- a/docs/index.md +++ b/docs/index.md @@ -5,55 +5,63 @@ title: Why Trivule? # Why Trivule? -**Trivule** is a user-friendly JavaScript library designed to simplify the dynamic validation of HTML forms on your web pages. +Trivule is a user-friendly JavaScript library designed to simplify dynamic form validation in HTML, offering several key features: -It was created to eliminate redundancy, save time, and reduce the complexity of form validation processes. By using intuitive HTML attributes, this library allows you to add complex and advanced validation rules without the need to know JavaScript. It aligns with the native logic of HTML validation, making the process simple, familiar, and seamless. +- Real-time validation with flexibility and ease. +- Time-saving and reduced complexity in validation processes. +- Easy integration into modern frameworks. +- Uniform usage in Vanilla JavaScript projects or modern frameworks. +- Excellent and intuitive message management. +- Validation without the need to master JavaScript code. -**Trivule** is an excellent option if you are looking for a quick way to implement complex validation on your site without having to write JavaScript code, regardless of your level of web development experience. +Trivule offers two validation approaches: -## Example +1. **Declarative Validation:** + This method allows validating a form using only HTML attributes. It supports event handling, rules, messages, and styling of an input based on its validity. Additionally, it automatically disables an entire form when all its fields are valid. +2. **Imperative Validation:** + This type of validation offers a more advanced approach by allowing more dynamic interaction with the form. It enables defining conditional validations and modifying validation rules during runtime. For example, it allows retrieving only valid or invalid fields from a form, or inserting an input with a validation state. + +Trivule is an excellent option if you're looking for a quick way to implement complex validation without wasting time or energy. + +**Declarative Validation:** ```html - -
- - -
-
-
- - -
-
-
- - -
-
-

- + ``` - -Result -![Capture d'écran de la validation](./screenshot.PNG) +**Imperative Validation:** +```javascript +trivuleForm.make([ + { + selector: "age", + rules: ["required","int", "min:18"], + }, +]); +``` +or +```javascript +trivuleForm.make({ + age: { + rules: ["required","int", "min:18"], + }, +}); +``` ## Validation Rules The validation rules in Trivule are predefined character strings that specify the conditions the form field values must meet. They are used as arguments in the `data-tr-rules` attribute. For example: ```html - + +``` +or +```javascript +trivuleForm.make({ + age: { + rules: "required|file|size:1MB", + }, +}) ``` - Explanation of the rules: - `required`: Indicates that the field is required. - `file`: Specifies that the value of the field must be a file. @@ -61,36 +69,112 @@ Explanation of the rules: [Learn more](/docs/rules/) -## Events - -In Trivule, validation is triggered by JavaScript events or custom events. By default, Trivule triggers validation during the following events: `blur`, `input`, and `change`. You can customize these events as desired. +In Trivule, validation is triggered by JavaScript events or custom events. By default, Trivule triggers validation on the following events: `blur`, `input`, or `change` depending on the type of input. You can customize these events as needed. -Unlike traditional JavaScript where you have to write event listeners, with Trivule, you don't need to worry about that. You can simply specify the desired events as a string, similar to how you do with validation rules. For example: +To specify the desired events, use the `data-tr-events` attribute as a string, similar to how you define validation rules. For example: ```html - + ``` -In this example, Trivule listens to the following events on the input element and triggers validation when they occur: -- `click`: Validation is executed and the validation status is indicated when the user clicks in the form field. -- `mouseenter`: Validation is triggered when the user hovers the cursor over the field. -- `my-custom-event`: Your own custom JavaScript event. +Once any of these events is triggered, Trivule proceeds with data validation. + +Usage through the declarative method: + +```javascript +{ + age: { + rules: [], + events: ['click', 'mouseenter', 'my-custom-event'] + } +} +``` -You can use predefined JavaScript events or specify your own custom events to trigger validation in a way that best suits your application. ## Messages -By default, validation messages are displayed in English on an HTML element (such as `div`, `p`, or `span`) with the attribute `data-tr-feedback="file"`. The messages are separated by the `|` symbol following the order of the rules. The `data-tr-feedback` attribute tells Trivule where to display your error messages. +Trivule comes with default error messages, but it also provides you with the flexibility to customize or translate messages into different languages and display them wherever you prefer. ```html - +
``` +or + +```javascript +trivuleForm.make([ + { + selector: "file", + rules: ["required", "mimes:text/plain"], + messages:['The file is required', 'The file must be a text file'.] + }, +]); +``` + +Trivule displays error messages at the nearest feedback element to the input. If you specify a general selector, it will be the first encountered element around the input. + -The flexibility offered by the ability to specify the message display location allows you to customize the message boxes as illustrated in the example below. +## Interaction with a Form -![Screenshot of validation](./nice-error.PNG) \ No newline at end of file +### Making a Form Validatable + +To make a form validatable, use the following syntax: + +```javascript +trivuleForm.make([ + { + selector: "name", + rules: ["required", "minlength:5", "upper"], + }, + { + selector: "age", + rules: ["int", "min:18"], + }, +]); +``` + +### Handling Validation Results + +To perform actions based on the validation results, + +#### 1. `onValidate` + +```javascript +trivuleForm.onValidate((form) => { + // Get validated input + form.validated(); + // Get all inputs + form.all(); + + // Get a single input + const ageInput = form.get('age'); + + // Prepend a rule to the existing list + ageInput.prepend({ + rule: "required", + message: "The age field cannot be empty" + }); +}); +``` + +#### 2. `onFails` + +```javascript +trivuleForm.onFails((form) => { + // Do something when the form is invalid +}); +``` + +#### 3. `onPasses` + +```javascript +trivuleForm.onPasses((form) => { + // Do something when the form is valid +}); +``` diff --git a/docs/input-validation.md b/docs/input-validation.md new file mode 100644 index 0000000..7d0a992 --- /dev/null +++ b/docs/input-validation.md @@ -0,0 +1,360 @@ +--- +sidebar_position: 3 +title: Input validation +--- + +## Trivule Form Input Validation + + +Trivule offers robust functionality for validating individual form fields with the `TrivuleInput` class, facilitating seamless interaction during the validation process. + +**Initialization** + +```javascript +const trivuleInput = new TrivuleInput({ + selector: "#username" +}); +``` + +**Customization Options** + +The `TrivuleInput` class allows for personalized validation behavior through the following options: + +- **`selector`:** Identifies the input element to validate using a CSS selector or DOM element reference. Required unless using the alternative `name` option. + +- **`feedbackElement` (optional):** Specifies where validation error messages are displayed, either through a CSS selector or by checking for an associated HTML element with the `data-tr-feedback` attribute set to the input's name. + +- **`rules` (required):** Defines validation criteria with an array or pipe-separated string of rules. + +- **`messages` (optional):** Maps rule names to custom error messages for failed validation. + +- **`name` (optional):** Alternative method to identify the input element using its name attribute. + +- **`events` (optional):** Array of events triggering input validation, including default events like form submission or blur, input, and change events. + +- **`autoValidate` (optional):** Determines whether to automatically validate input on specified events or upon form submission. + +- **`attribute` (optional):** Specifies the HTML attribute for displaying error messages, offering flexibility in error message placement. + +- **`failsOnFirst` (optional):** Controls whether validation stops at the first encountered error, potentially improving user experience by limiting error messages. + +- **`emitEvent` (optional):** Emits a `"tr.input.validated"` event after each validation, allowing for custom listeners based on validation results. + +- **`validClass` (optional):** CSS class applied to valid input elements for visual feedback. + +- **`invalidClass` (optional):** CSS class applied to invalid input elements to guide users toward corrections. + +- **`type` (optional):** Specifies the input element type for type-specific validation rules or behavior. + +- **`realTime` (optional):** Enables real-time validation during user input, providing immediate feedback as users interact with the form. + +These options empower developers to tailor validation behavior to suit their application's needs, enhancing user experience and error handling. + +## Handling Validation Status + +With the `TrivuleInput` class, you can effectively respond to the validation status of an input element using event listeners. These listeners trigger custom actions based on whether the input passes or fails validation. + +**1. `onFails(fn: EventCallback)`** + +- Attaches a listener to the `"tr.input.fails"` event, activated when the input fails validation. +- Define a callback function (`fn`) that takes a `TrivuleInput` object as its argument. + +**Example:** + +```typescript +trivuleInput.onFails((trivuleInput) => { + // Handle failed validation +}); +``` + +**2. `onPasses(fn: EventCallback)`** + +- Attaches a listener to the `"tr.input.passes"` event, triggered upon successful validation of the input. +- Define a callback function (`fn`) that takes a `TrivuleInput` object as its argument. + +**Example:** + +```typescript +trivuleInput.onPasses((event) => { + console.log("Input passed validation!"); +}); +``` + +**Choosing the Approach:** + +Utilize `onFails` to address validation failures and `onPasses` for successful validation. Alternatively, directly listen to the `"tr.input.fails"` or `"tr.input.passes"` events for streamlined event handling, optimizing your form's responsiveness. + + + +### Efficient Validation Check: `valid()` + +The `valid()` method in the `TrivuleInput` class enables you to discreetly validate an input element without triggering external events, such as `"tr.input.passes"` or `"tr.input.fails"`. This method is valuable when you need to assess validation status internally for specific actions or logic without altering the standard event-driven validation flow. + +**Functionality:** + +- Conducts validation on the input element according to the defined validation rules. +- **Does not dispatch** `"tr.input.passes"` or `"tr.input.fails"` events. +- Returns `true` if the input element satisfies all validation rules and is deemed valid. +- Returns `false` if the input element violates any of the validation rules, indicating validation failure. + +**Example Usage:** + +```typescript +// Perform silent validation +const isValid = trivuleInput.valid(); + +if (isValid) { + console.log("Input is valid!"); +} else { + console.log("Input failed validation."); +} +``` + +- This method operates independently of event triggering; thus, attached event listeners for `"tr.input.passes"` or `"tr.input.fails"` will not be activated. +- For validation management reliant on event-driven behavior and user feedback, consider employing the `onFails` and `onPasses` methods outlined previously. + +### Validating Inputs with `validate()` + +The `validate()` method in the `TrivuleInput` class orchestrates a thorough validation process for input elements, offering comprehensive feedback and event handling. + +**Functionality:** + +- Conducts validation using predefined rules, akin to the `valid()` method, and returns a boolean indicating validation success or failure. +- Optionally emits the `"tr.input.validated"` event if `emitOnValidate` is set to true. +- Applies validation classes to the input element for visual cues. +- Displays feedback messages to users for clearer understanding of validation outcomes. + +**Example Usage:** + +```typescript +// Validate the input element +const isValid = trivuleInput.validate(); + +// Process validation outcome +if (isValid) { + console.log("Input is valid!"); +} else { + console.log("Input failed validation."); + const errors = trivuleInput.errors; +} +``` + +**Key Considerations:** + +- Utilize `validate()` for a comprehensive validation cycle, encompassing event emission and potential visual feedback. +- For silent validation checks within your form logic, `valid()` provides a suitable alternative. + +### Custom Event Handling with `emit()` + +The `emit()` method in the `TrivuleInput` class facilitates the emission of custom events to the input element, enabling customized event-driven interactions within your application. + +#### Functionality + +- **Emits Custom Events:** Allows emission of custom events to the input element. +- **Event Name:** Specify the name of the custom event to emit. +- **Additional Data:** Optionally include additional data to pass along with the event. + +#### Parameters + +- **`e`:** The name of the custom event to emit. +- **`data` (optional):** Additional data to pass with the event. + +#### Example Usage + +```typescript +// Emit a custom event named "inputChange" +trivuleInput.emit("inputChange"); + +// Emit a custom event with additional data +trivuleInput.emit("inputSubmit", { value: inputValue }); +``` + +### Event Listener Attachment with `on()` + +The `on()` method in the `TrivuleInput` class allows you to attach event listeners to the input element, enabling responsive handling of various events triggered by user interactions or application logic. + +#### Functionality + +- **Attach Event Listeners:** Enables attachment of event listeners to the input element. +- **Event Name:** Specify the name of the event to listen to. +- **Callback Function:** Define a callback function to execute when the specified event occurs. + +#### Parameters + +- **`e`:** The name of the event to listen to. +- **`fn`:** The callback function to execute when the event occurs. This function takes an event of type `Event` as a parameter and returns nothing. + +#### Example Usage + +```typescript +// Attach an event listener for the "change" event +trivuleInput.on("change", (event) => { + console.log("Input value changed:", event.target.value); +}); + +// Attach an event listener for a custom event +trivuleInput.on("inputSubmit", (event) => { + console.log("Input submitted with value:", event.detail.value); +}); +``` + +These methods empower you to create dynamic and interactive user experiences by enabling custom event emission and event listener attachment within your application's input elements. + +## Rules + +### Extending Validation Rules with `pushRule()` and `appendRule()` + +Both the `pushRule()` and `appendRule()` methods in the `TrivuleInput` class empower developers to enhance the validation capabilities of Trivule input instances by adding custom validation rules tailored to specific requirements. While they serve similar purposes, `appendRule()` acts as an alias for `pushRule()`, providing flexibility in method naming. + +#### Functionality + +- **Add Rule:** Both methods allow developers to incorporate additional validation rules into the existing set of rules for a Trivule input instance. +- **Rule Specification:** Specify the name of the rule to be added. + - **`rule`:** The name of the rule to be added. +- **Optional Parameters:** + - **`message`:** Custom error message associated with the added rule. + - **`param`:** Additional parameter(s) required for the validation rule. + - **`validate`:** Custom validation callback function for the added rule. + - **`local`:** Language localization for error messages. + +#### Returns + +- **This Trivule Input Instance:** Both methods return the current Trivule input instance, enabling method chaining for enhanced readability and simplicity. + +#### Example Usage + +```typescript +// Add an additional validation rule for minimum length using pushRule() +trivuleInput.pushRule({ + rule: "minLength", + param: 8, + message: "Password must be at least 8 characters long.", +}); + +// Incorporate a custom validation rule with a custom validation callback function using appendRule() +trivuleInput.appendRule({ + rule: "customRule", + validate: (value) => { + return { + passes: value === "customValue", + value: value.trim() + }; + }, + message: "Input must be 'customValue'.", +}); +``` + +By offering both `pushRule()` and `appendRule()` methods, developers have flexible options for extending the validation capabilities of Trivule input instances, enhancing the overall flexibility and adaptability of input validation processes. + +### Modifying Validation Rules with `prependRule()`, `insertAfterRule()`, and `insertBeforeRule()` + +The `prependRule()`, `insertAfterRule()`, and `insertBeforeRule()` methods in the `TrivuleInput` class offer developers versatile options to modify and rearrange validation rules within Trivule input instances. These methods enable dynamic adjustments to the validation process, enhancing flexibility and customization. + +#### Functionality + +- **Prepend Rule (`prependRule()`):** Adds a validation rule to the beginning of the existing rule set for the Trivule input instance. +- **Insert After Rule (`insertAfterRule()`):** Inserts a new validation rule after a specified existing rule within the rule set. +- **Insert Before Rule (`insertBeforeRule()`):** Inserts a new validation rule before a specified existing rule within the rule set. +- **Rule Specification:** Define the name of the rule to be added or inserted. + - **`rule`:** The name of the rule to be added or inserted. +- **Optional Parameters:** + - **`oldRule`:** The existing rule after which the new rule will be inserted (`insertAfterRule()` and `insertBeforeRule()` only). + - **`newRule`:** The new rule to be added or inserted. + - **`message`:** Custom error message associated with the added or inserted rule. + - **`param`:** Additional parameter(s) required for the validation rule. + - **`validate`:** Custom validation callback function for the added or inserted rule. + - **`local`:** Language localization for error messages. + +#### Returns + +- **This Trivule Input Instance:** All methods return the current Trivule input instance, facilitating method chaining for enhanced readability and simplicity. + +#### Example Usage + +```typescript +// Prepend a validation rule to the existing rule set +trivuleInput.prependRule({ + rule: "required", + message: "Field is required.", +}); + +// Insert a new validation rule after an existing rule +trivuleInput.insertAfterRule({ + oldRule: "minLength", + newRule: "customRule", + validate: (value) => { + return { + passes: value === "customValue", + value: value.trim() + }; + }, + message: "Input must be 'customValue'.", +}); + +// Insert a new validation rule before an existing rule +trivuleInput.insertBeforeRule({ + oldRule: "maxLength", + newRule: "customRule", + validate: (value) => { + return { + passes: value === "customValue", + value: value.trim() + }; + }, + message: "Input must be 'customValue'.", +}); +``` + +By offering these methods, developers gain the flexibility to dynamically modify the validation rule set of Trivule input instances, allowing for tailored validation processes that meet specific application requirements. + + +## Useful methods + +### Retrieving Feedback Element with `getFeedbackElement()` + +The `getFeedbackElement()` method in the `TrivuleInput` class facilitates the retrieval of the feedback element associated with the input element. This method provides access to the HTML element where validation error messages are displayed, enabling developers to customize or manipulate feedback presentation as needed. + +#### Functionality + +- **Retrieve Feedback Element:** Returns the HTML element designated for displaying validation error messages associated with the input element. + +#### Returns + +- **Feedback Element:** The HTML element where validation error messages are displayed. + +#### Example Usage + +```typescript +// Retrieve the feedback element +const feedbackElement = trivuleInput.getFeedbackElement(); + +// Manipulate the feedback element (e.g., customize styling or content) +feedbackElement.classList.add("custom-feedback"); +feedbackElement.innerHTML = "Custom error message"; +``` + +By utilizing the `getFeedbackElement()` method, developers can seamlessly access and modify the feedback element associated with Trivule input instances, enhancing the visual presentation and user experience of validation error messages. + +### Retrieving Validation Messages with `getMessages()` + +The `getMessages()` method in the `TrivuleInput` class allows you to obtain the validation messages associated with the input element. This method returns an object containing the validation messages, providing developers with insight into the specific error messages configured for the input's validation rules. + +#### Functionality + +- **Retrieve Validation Messages:** Returns an object containing the validation messages associated with the input element. + +#### Returns + +- **Validation Messages Object:** An object containing the validation messages configured for the input element's validation rules. + +#### Example Usage + +```typescript +// Retrieve validation messages +const messages = trivuleInput.getMessages(); + +// Log validation messages to the console +console.log(messages); +``` + +By utilizing the `getMessages()` method, developers can easily access and review the validation messages assigned to the input element, facilitating effective error message management and customization for enhanced user experience. \ No newline at end of file diff --git a/docs/installation.md b/docs/installation.md index 96eda87..994c1d3 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -5,40 +5,38 @@ title: Installation # Installation -## Downloading or Using CDN +## Download or Use CDN -To use Trivule, follow these steps: +To use Trivule in your project, follow these steps: -1. **[Download](https://cdn.jsdelivr.net/npm/trivule@1.0.0/dist/index.umd.js)** the Trivule library from [here](https://cdn.jsdelivr.net/npm/trivule@1.0.0/dist/index.umd.js). Alternatively, you can directly use the link: `https://cdn.jsdelivr.net/npm/trivule@1.0.0/dist/index.umd.js`. +1. **[Download](https://cdn.jsdelivr.net/npm/trivule@latest/dist/index.umd.js)** the Trivule library from [here](https://cdn.jsdelivr.net/npm/trivule@latest/dist/index.umd.js). Alternatively, you can use the CDN link directly: `https://cdn.jsdelivr.net/npm/trivule@latest/dist/index.umd.js`. 2. Include the Trivule library in your web page as you would any other JavaScript file. ## Installation via npm -1. Go to your project directory and enter the following command: +1. Navigate to your project directory and run the following command: ```bash npm i trivule ``` -After installation, you can use Trivule in your project as needed: +Once installed, you can use Trivule in your project as needed: -- For a single form field: +- For validating a single form field: ```js -import { TrInput } from 'trivule'; -const trInput = new TrInput('selector'); -trInput.init(); +import { TrivuleInput } from 'trivule'; +const trInput = new TrivuleInput('selector'); ``` -- For an entire form: +- For validating an entire form: ```js -import { TrForm } from 'trivule'; -const trForm = new TrForm('selector'); -trForm.init(); +import { TrivuleForm } from 'trivule'; +const trForm = new TrivuleForm('selector'); ``` -- For all forms: +- For validating all forms in your project, suitable for classic HTML/CSS projects (vanilla), but also supports declarative validation: ```js import { Trivule } from 'trivule'; @@ -46,7 +44,8 @@ const tr = new Trivule(); tr.init(); ``` -## Complete Example +## Example +Here's an example of validation that doesn't require JavaScript: ```html
@@ -76,7 +75,7 @@ tr.init();

- + +``` + +## Step 2: Form Validation -First, add the Trivule library from [this link](https://cdn.jsdelivr.net/npm/trivule@1.0.0/dist/index.umd.js) to your code. +Create an HTML form with fields to validate using Trivule. + +### Imperative Validation ```html - +
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+

+ +

+
``` -## Step 2: Define the Form -Create a blank page for testing and add the following HTML code. +```js +const trivuleForm = new TrivuleForm("form", { + feedbackSelector: ".invalid-feedback", +}); + +trivuleForm.make({ + name: { + rules: "required|between:2,80|only:string", + }, + email: { + rules: "required|email|maxlength:32", + }, + message: { + rules: "required|between:2,250|endWith:.", + messages: { + endWith: "The message must end with a period (.)", + } + } +}); +``` -We will create an HTML form with fields to validate using Trivule. +#### Form Submission -Here's an example: +You can use the `onPasses` method to be notified when the form is valid. + +```js +trivuleForm.onPasses((trivuleForm)=>{ + const allInputs = trivuleForm.inputs(true); +}) +``` + +Alternatively, the `onFails` method allows you to be notified when the form is invalid. + +```js +trivuleForm.onFails((trivuleForm)=>{ + // Do something +}) +``` + +To prevent form submission, which is not mandatory as Trivule will prevent submission if it's not valid by default: + +```js +trivuleForm.on('submit', (e)=>{ + if(!trivuleForm.valid){ + e.preventDefault(); + } +}) +``` + +### Declarative Validation ```html
-
- -
- -
-
-
-
- - -
-
-
- - -
-
-
- - -
-
-

- -

+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+

+ +

``` In this example, we have added `data-tr-rules` attributes to the form fields to specify validation rules and `data-tr-feedback` attributes to certain `div` elements to display validation feedback. +## Step 3: Initialize Trivule + +Now that we've defined our form, let's link it to Trivule to perform validation. Add the following JavaScript code at the end of your page, just before the closing `` tag: + +```html + +``` + +And that's it! Now, when you submit the form or when field values change, Trivule will validate according to the rules you've defined and display appropriate validation feedback. + +Feel free to customize the validation rules and error messages according to your needs. You can also refer to the Trivule documentation for more information on advanced features. + +I hope this tutorial was helpful for you to get started with Trivule with a concrete example. Have fun validating your forms with ease! + +## Further Reading + +Trivule offers many customization and configuration options to meet your specific needs. Here are some additional resources to help you explore these features: + +- [Customizing Messages](/docs/messages): Learn how to customize the error messages and text displayed by Trivule. +- [Other Validation Rules](/docs/rules): Explore the different validation rules available in Trivule, such as length validation, regular expression validation, and more. +- [Validation Events](/docs/events): Learn about validation events to interact with Trivule during form validation. +- [Validating Individual Inputs](/docs/validation/tr-input): Discover how to validate an individual form field with Trivule. +- [Validating an Individual Form](/docs/validation/tr-form): Learn how to validate a specific form using Trivule. +- [Validating Forms on a Page](/docs/validation/trivule): Discover how to validate all forms on a page at once. +- [Examples](/docs/example): Check out real-world examples of Trivule's use for form validation. +- [Framework Integration (React, Angular, etc.)](#): Get instructions on integrating Trivule into popular frameworks like React, Angular, Vue.js, etc. +- [Contribution](/docs/contribution): Contribute to Trivule's development by providing suggestions, bug reports, or proposing improvements. +- [Development](/docs/contribution): If you are interested in Trivule development, see this documentation for information on how to contribute to the project. + +These resources will help you deepen your knowledge and make the most of Trivule for your form validation. Enjoy the power and flexibility of Trivule in your projects! + ### Form Style -To create a clean form style, add the following CSS code to your page. -You can customize it as you like. +To create a clean form style, add the following CSS code to your page. You can customize it as you like. + ```css form { width: 80%; @@ -209,39 +304,3 @@ p { margin-bottom: 10px; } ``` - -## Step 3: Initialize Trivule - -Now that we've defined our form, let's link it to Trivule to perform validation. Add the following JavaScript code at the end of your page, just before the closing `` tag: - -```html - -``` - -In this example, we create an instance of `Trivule` and call the `init()` method to initialize the validation. - -And that's it! Now, when you submit the form or interact with the fields, Trivule will validate according to the rules you've defined and display appropriate validation feedback. - -Feel free to customize the validation rules and error messages according to your needs. You can also refer to the Trivule documentation for more information on advanced features. - -I hope this tutorial was helpful for you to get started with Trivule with a concrete example. Have fun validating your forms with ease! - -## Further Reading - -Trivule offers many customization and configuration options to meet your specific needs. Here are some additional resources to help you explore these features: - -- [Customizing Messages](/docs/messages): Learn how to customize the error messages and text displayed by Trivule. -- [Other Validation Rules](/docs/rules): Explore the different validation rules available in Trivule, such as length validation, regular expression validation, and more. -- [Validation Events](/docs/events): Learn about validation events to interact with Trivule during form validation. -- [Validating Individual Inputs](/docs/validation/tr-input): Discover how to validate an individual form field with Trivule. -- [Validating an Individual Form](/docs/validation/tr-form): Learn how to validate a specific form using Trivule. -- [Validating Forms on a Page](/docs/validation/trivule): Discover how to validate all forms on a page at once. -- [Examples](/docs/example): Check out real-world examples of Trivule's use for form validation. -- [Framework Integration (React, Angular, etc.)](#): Get instructions on integrating Trivule into popular frameworks like React, Angular, Vue.js, etc. -- [Contribution](/docs/contribution): Contribute to Trivule's development by providing suggestions, bug reports, or proposing improvements. -- [Development](/docs/contribution): If you are interested in Trivule development, see this documentation for information on how to contribute to the project. - -These resources will help you deepen your knowledge and make the most of Trivule for your form validation. Enjoy the power and flexibility of Trivule in your projects! \ No newline at end of file diff --git a/docs/validation/index.md b/docs/validation/index.md deleted file mode 100644 index badd93a..0000000 --- a/docs/validation/index.md +++ /dev/null @@ -1,53 +0,0 @@ ---- -sidebar_position: 11 -title: Validations ---- - -# Validation -Validation is a crucial aspect of managing forms in web applications. In this documentation, we will explore the concepts related to validation in Trivule and guide you through the different features offered by the library for validating fields and forms. - -To make navigation easier, here are the different sections of the documentation on validation: - -## Field Validation - -In this section, you will learn how to individually validate form fields using Trivule. We will explain how to define validation rules, triggering events, custom error messages, and more. - -[Field Validation](/docs/validation/tr-input) - -## Form Validation - -This section focuses on form validation in Trivule. You will discover how to configure validation for an entire form using the appropriate Trivule attributes. We will also cover additional features such as automatic validation, customizing CSS classes, and validation events. - -[Form Validation](/docs/validation/tr-form) - -## Validation Rules - -Validation rules are the conditions that fields must satisfy to be considered valid. In this section, we will review the predefined validation rules available in Trivule, such as minimum length, email format, regex matching, and more. You will learn how to use these rules in your forms. - -[Validation Rules](/docs/rules/) - -## Validation Attributes - -Trivule uses HTML attributes to configure and customize the validation of fields and forms. In this section, we will detail the most commonly used Trivule attributes, explaining their purpose, use cases, and providing examples to illustrate their use. - -[Validation Attributes](/docs/attributes/) - -## Validation Events - -Validation events allow you to control when and how field validation should be triggered. In this section, we will explore the validation events supported by Trivule and show you how to use them to customize the validation behavior of your forms. - -[Validation Events](/docs/events/) - -## Validation Messages - -Validation messages are error messages displayed when fields do not satisfy validation rules. In this section, you will discover how to customize validation messages in Trivule using the appropriate attributes. We will also show you how to handle validation messages in different languages. - -[Validation Messages](/docs/messages/) - -## Global Validation - -Trivule also offers global validation features to facilitate the management of validation at the application level. In this section, you will discover how to configure and use Trivule to validate multiple forms or fields simultaneously and how to handle global validation errors. - -[Global Validation](/docs/validation/trivule) - -We hope this documentation helps you master validation in Trivule and easily integrate form validation into your web applications. If you have additional questions, feel free to consult the detailed documentation for each section or join our [community on Discord](https://discord.gg/wPPAfq5n) for assistance from the Trivule community. \ No newline at end of file diff --git a/docs/validation/tr-form.md b/docs/validation/tr-form.md deleted file mode 100644 index 1b5a0fd..0000000 --- a/docs/validation/tr-form.md +++ /dev/null @@ -1,260 +0,0 @@ ---- -sidebar_position: 13 -title: Form Validation ---- - -# Form Validation - -Form validation refers to the validation of an HTML form in its entirety. In practice, form validation is developed based on [input validation](/docs/validation/tr-input). It encompasses actions such as disabling the submit button and preventing the propagation of the `submit` event of a form. - -## TrForm - -### Interaction with Forms during Validation - -Let's consider the following form: - -```html -
-
- - -
-
-
- - -
-
-

- -

-
-``` - -Let's initialize it: - -```js -const trForm = new TrForm("form"); -trForm.init(); -``` - -By initializing the form, Trivule will attach the appropriate event handlers to the form and its fields. This setup ensures that when the form is submitted, the fields are validated according to the specified rules. If any field fails validation, the submit event is prevented, and appropriate feedback is displayed to the user. - -The `data-tr-rules` attribute is used to specify the validation rules for each input field, such as requiring a field to be filled (`required`), specifying the format (`email`), or setting constraints on length (`maxlength:32`). The `data-tr-feedback` attribute specifies where the feedback messages should be displayed. - -Once the form is initialized, Trivule takes care of handling form submissions and providing feedback based on the validation rules. - - -### `onInit` - Before Validation - -When using Trivule for live form validation, additional actions may be needed after form initialization. For example, specific configurations or object manipulations may be required to prepare the form for more advanced interaction. - -The `onInit` method addresses this by providing a clean way to attach event handlers that will be triggered specifically after initialization. This allows you to perform custom actions or configure additional features in response to the form's ready state. - -The `onInit()` method should be called before calling the `init()` method. - -#### Example Usage - -```typescript -trForm.onInit((initializedForm: TrForm) => { - console.log("The form is ready for additional actions:", initializedForm); -}); -``` - -In this example, the `onInit` method is called with a callback function that logs a message when the form is ready for further actions. This method provides a way to execute custom actions or additional configurations in response to the form's initialization. - -#### Use Cases - -- **Custom Configuration:** Perform specific configurations for the form after its initialization. - -- **Post-Initialization Actions:** Execute actions that depend on the full preparation of the form. - -*Note: It is advisable to use `onInit` judiciously for tasks unrelated to validation, as full form initialization may not guarantee the completion of asynchronous validations or other deferred tasks.* - -### `onFails` & `onPasses` - Dynamic Validation Responses - -The `onFails` and `onPasses` methods of the `TrForm` class provide complete flexibility to dynamically respond to the successes and failures of form field validations. - -#### `onFails` - Failed Validation - -The `onFails` method allows you to define an event handler that will be triggered whenever a form field fails validation. Example: - -```javascript -trForm.onFails((trFormInstance) => { - // Code to execute in case of validation failure - console.log("Validation failed", trFormInstance); - // Customize the reactions to validation failures here -}); -``` - -Customize the code to execute according to your needs. - -#### `onPasses` - Successful Validation - -The `onPasses` method works similarly, triggering an event handler when the form passes validation. Example: - -```javascript -trForm.onPasses((trFormInstance) => { - // Code to execute in case of successful validation - console.log("Validation succeeded"); - // Customize reactions to validation successes here -}); -``` - -Use this method to perform specific actions in case of successful validation, such as validating other fields or enabling a submit button. - -By leveraging `onFails` and `onPasses`, you can tailor your application to the validation outcomes of the form fields, adding customized and responsive logic. - -### Custom Event Emission - -### `emit` - Event Customization - -The `emit` method of the `TrForm` class allows you to emit custom events to the form associated with the `TrForm` instance. This advanced feature facilitates communication and interaction within your application. - -#### Example Usage - -```javascript -const userData = { name: "John Doe", age: 25 }; - -// Emitting a custom "user-updated" event with additional data -trForm.emit("user-updated", userData); -``` - -In this example, a custom event named "user-updated" is emitted to the form, carrying additional user data. This flexibility allows you to create scenarios where specific parts of your application can respond to these tailored events. - -#### Possible Uses - -- **Advanced Communication:** Emit events when an `input` element's value changes and listen for these events to trigger specific actions in different parts of your application. - -- **Customizing Interactions:** Adapt your application's behavior by emitting custom events in response to specific conditions or form states. - -- **Integration with Other Components:** Facilitate integration with other components of your application by emitting events containing crucial information. - -Wise use of the `emit` method can greatly enhance your application's interactivity and modularity, allowing different parts to respond in a customized way to events emitted by the `TrForm` class. - -### Attaching Event Listeners - -The `on` method of the `TrForm` class opens up a world of opportunities by allowing you to attach event listeners, whether they are native or custom events, to your form. Learn how to customize your user experience by dynamically responding to specific interactions. - -#### Example Usage - -```javascript -// Attach an event listener for the "change" event -trForm.on("change", (event) => { - // Code to execute when the "change" event occurs in the form - console.log("Change detected!"); -}); -``` - -In this example, an event listener is added to the form for the "change" event. When this event occurs, the code inside the callback function is executed. You can listen for other events such as "submit," "click," or even your own custom events. - -#### Possible Uses - -- **User Interaction Responsiveness:** Monitor events such as change (`change`), click (`click`), or submit (`submit`) to trigger specific actions. - -- **Custom Validation:** Attach a listener to respond to custom events emitted by the `TrForm` class and perform validations or specific actions accordingly. - -- **Integration with Other Components:** Create harmonious interactions with other parts of your application by listening to specific events emitted by other components. - -By skillfully incorporating the `on` method, you can customize the user experience and add intelligent responsiveness to your form, making your application an interactive and dynamic experience. - -### Form Validation Status - -The `passes` method in the `TrForm` class checks whether the form is valid or not. - -#### Example Usage - -```javascript -// Check if the form is valid -const isValid = trForm.passes(); - -if (isValid) { - // Proceed with form submission or handle a valid form -} else { - // Display error messages or handle an invalid form -} -``` - -In this example, the `passes` method is called to determine whether the form is valid. Based on the result, you can decide to submit the form, display error messages to the user, or perform other customized actions. - -#### Possible Uses - -- **Conditional Submission:** Use `passes` before triggering form submission to ensure all validations have been successfully passed. - -- **Dynamic Response:** Customize your application behavior based on the current validation status of the form. - -- **Error Handling Logic:** Display targeted error messages or take specific actions in case of validation failure. - -The `passes` method calls the internal `isValid` method that checks each field according to the defined validation rules. By incorporating it into your logic, you can create a robust and responsive user experience. Take control of your form validation with the `passes` method from `TrForm`. - -### `onValidate()` - Reacting to Form Validation - -The `onValidate()` method of the `TrForm` class allows you to react to the form validation event. Use this feature to execute specific actions when complete form validation is performed. - -#### Example Usage - -```javascript -trForm.onValidate((trForm) => { - console.log("Form validation performed", trForm); -}); -``` - -### Destroying TrForm Instance - -The `destroy` method of the `TrForm` class allows you to reset the `TrForm` instance by removing custom validation rules and associated event listeners. Here is an example of usage: - -```javascript -trForm.destroy(); -``` - -In this example, the `destroy` method is called on the `trForm` instance. This removes all custom validation rules and event listeners associated with this instance. - -You can use the `destroy` method when you want to reset the `TrForm` instance to its initial state, such as when removing or deactivating the form. - -By using the methods and events provided by the `TrForm` class, you can customize your form's validation and interaction in your application. Whether reacting to successful or failed validation events, emitting custom events, listening to form events, or performing specific validations, you have the ability to add custom logic to your application based on the form validation results. - -The `isValid` method of the `TrForm` class checks whether the form is valid. It returns a boolean value indicating whether all form fields, represented by `TrInput` instances attached to the `TrForm` class, are valid. - -Here's an example usage: - -```javascript -const trForm = new TrForm(formElement); - -const isValid = trForm.isValid(); -if (isValid) { - // The form is valid - // Perform desired actions, such as submitting the form -} else { - // The form is not valid - // Perform desired actions, such as displaying an error message -} -``` - -In this example, a `TrForm` instance is created with the form element `formElement`. Then, the `isValid` method is called on this instance to check if the form is valid. The return value, `isValid`, will be `true` if all form fields are valid, and `false` otherwise. - -You can use this method to make decisions in your code based on the form's validity. For example, if the form is valid, you may submit the form or perform other desired actions. If the form is not valid, you can display an error message or prevent form submission. - -The `isValid` method iterates over all `TrInput` instances attached to the `TrForm` class using the `every` method. It calls the `passes` method on each `TrInput` instance to check if the field is valid. If all fields pass validation, the `isValid` method returns `true`. Otherwise, it returns `false`. - -By using the `isValid` method, you can easily verify the overall validity of the form based on the individual validation of each field. - -The `observeChanges` method of the `TrForm` class allows you to attach an event listener to the "tr.form.updated" event. When this event is triggered, the method initializes and executes the `TrInputs` for the form, then calls the provided function with the form instance as a parameter. - -Here's an example usage: - -```javascript -trForm.observeChanges((form) => { - console.log("Form updated", form); -}); -``` - -In this example, the `observeChanges` method is called on the `trForm` instance with a callback function that displays a message in the console when the "tr.form.updated" event is triggered. The callback function takes the form instance `form` as a parameter. - -When the "tr.form.updated" event is triggered, the `observeChanges` method destroys the current form instance by calling the `destroy` method, then reinitializes the form by calling the `setContainer` method with the original container. Next, the `TrInputs` are initialized by calling the `_initTrInputs` method, then executed by calling the `_runTrInputs` method. Finally, the provided callback function is called with the form instance as a parameter. - -Using the `observeChanges` method allows you to monitor changes in the form and take specific actions in response to those changes. You can reset and update the `TrInputs`, as well as execute custom code when the form is updated. \ No newline at end of file diff --git a/docs/validation/tr-input.md b/docs/validation/tr-input.md deleted file mode 100644 index e1e1a66..0000000 --- a/docs/validation/tr-input.md +++ /dev/null @@ -1,360 +0,0 @@ ---- -sidebar_position: 12 -title: Input validation ---- - -# Input validation - -### TrInput -In Trivule, you have the option to individually validate form fields. Throughout this documentation, we will use the term "`field`" or "`input`" to refer to a specific form field **(form input)** that is subject to validation. - - -The `TrInput` class is a core component of Trivule that enables individual input validation. The `TrForm` class utilizes `TrInput` to validate a set of inputs. Each time validation is performed, whether it fails or passes, the class emits the corresponding event, allowing you to determine the overall validity of the form. - -## Initialization - -First and foremost, when initializing an instance of this class, it sets up the `rules`, `messages`, and other values defined on the input element using `data-tr` attributes or the second argument of it constructor, which is an object of type `TrInputParams`. - -```javascript - const trInput = new TrInput("input") -``` -The first constructor argument should be a [`ValidatableInput` ](#) - -This assumes you have an input on your page that has the ID #my-input. -This input would have its validation dependencies via data-tr attributes -```html - -``` -Rather than setting the `data-tr` attributes this way, you have the option of directly passing a `TrInputParams` object with the same parameters: - -```javascript -const inputElement = document.querySelector("#my-input"); -const trInput = new TrInput(inputElement, { - rules: ['required', 'min:8'], - invalidClass: 'is-invalid', - events: ['blur', 'change', 'input'], -}); -``` - -This allows you to specify the validation `rules`, the class to apply in case of invalidity (`invalidClass`), the events that trigger validation (`events`) directly in the `TrInputParams` object. - -Thus, you can easily customize the validation parameters for the `` element by grouping all the relevant information into a single object. - -Indeed, you can use the `with` method of the `trInput` instance to set validation parameters by passing a `TrInputParams` object. Here's how you can use it: - -```javascript -const trInput = new TrInput("#my-input"); -trInput.with({ - rules: ['required', 'min:8'], - invalidClass: 'is-invalid', - events: ['blur', 'change', 'input'], -}); -``` - -By calling the `with` method and passing the `TrInputParams` object, you can define the validation rules, the css class to apply in case of invalidity (`invalidClass`), the events that trigger validation (`events`) in a more concise and readable way. - -This allows you to customize validation settings directly after creating the `trInput` instance, making it easier to configure the validation object. - -```javascript -trInput.init(); -``` - -Once this setup is complete, calling the `init` method starts listening to the events specified by the `data-tr-events` attribute or the `events` property in the `TrInputParams` object. -When one of these events is triggered, the defined validation rules are executed in the order they were defined. - -## Rules Assignment - -Assigning rules to an input field is an essential step in the validation process. To do this, you can use either the `data-tr-rules` attribute in your HTML tag, or the `rules` attribute of the `TrInputParams` object when initializing the `trInput` instance. - -Here is an example illustrating this assignment: - -```html - -``` - -In this example, we have assigned two rules to the input field. The first rule, `required`, specifies that the input field must be filled. The second rule, `min:8`, specifies that the input field must contain at least 8 characters. - -You can also assign validation rules using the `rules` attribute when configuring the `trInput` instance: - -```javascript -trInput.with({ - rules: ['required', 'min:8'], - // Other parameters... -}); -``` - -This programmatic approach provides additional flexibility for defining validation rules. - -By using these attributes, you can easily specify validation rules for your input fields. - -**Important Note:** The field validation will be performed in the order of rule definition. It is crucial to consider the order of rules when validating a specific field. For example, if you want to validate a file field and specify the rule `maxFileSize:2MB` before the `file` rule, **Trivule** will do its best to validate the field accordingly. However, unexpected outcomes may occur if the rules are not defined in the intended order. - -## Validation trigger - -You have the ability to define your own custom JavaScript events that trigger the validation process. By default, the events used are `blur`, `input` and `change`. However, if you want to customize these events, you can do so by using the `data-tr-events` attribute on your HTML elements or by using the `events` attribute of the `TrInputParams` object. - -When using the `data-tr-events` attribute on an HTML element, you can specify the events separated by the `|` symbol. For example : - -```html - -``` - -In this example, validation will be triggered on the `focus`, `input` events, as well as the `myCustomEvent` custom event. - -If you prefer to use the `events` attribute of the `TrInputParams` object when creating a `TrInput` instance, you can pass an array of JavaScript events. For example : - -```javascript -const trInput = new TrInput("#my-input", { - events: ["focus", "input", "myCustomEvent"], -}); -``` - -This way, the same `focus`, `input` and `myCustomEvent` events will be used to trigger validation. - -Feel free to customize validation events to your specific needs using either of these methods. - -## Validation error style - -It is common to visually indicate the validation status of form fields by applying specific CSS classes. You can easily add a CSS class to your input field when it is valid or invalid using the `data-tr-invalid-class` or `data-tr-valid` attributes, or the `invalidClass` or ` validClass` of the `TrInputParams` object. - -The default class to represent the invalid state of a form field is `is-invalid`. This means that if you don't explicitly specify the class to use with the `data-tr-invalid-class` or `invalidClass` attribute of the TrInputParams object, the '`is-invalid`' class will be automatically added to your input field when the validation fails. - -The `data-tr-invalid-class` attribute allows you to specify the CSS class that will be added to your input field when it is invalid. For example : - -```html - -``` - -In this example, the CSS class "error" will be applied to the `` element when validation fails. - -Similarly, you can use the `data-tr-valid` attribute to specify the CSS class that will be added to your input field when it is valid. - -If you prefer to use the `invalidClass` or `validClass` attribute of the `TrInputParams` object when creating a `TrInput` instance, you can do so as follows: - -```javascript -const trInput = new TrInput("#my-input", { - invalidClass: "error", -}); -``` - -In this example, the "`error`" CSS class will be added to the input element when validation fails. - -Feel free to customize the CSS classes for the validation state of your form fields using these attributes or options, to achieve the desired visual appearance based on the validation state. - - -## Messages -### Customizing error messages - -Suppose you have a form with two fields: "Name" and "Email". You want to specify specific error messages for each field other than the Trivule default messages. - -For the "Name" field, you want to display the message "**Name is mandatory**" if no value is entered. For the "Email" field, you want to display the message "**Please enter a valid email address**". - -You can use the `data-tr-messages` attribute to customize error messages for each field. Here's how you can do it: - -```html - - - -``` - -With this configuration, Trivule will display specific error messages when the corresponding rules are not respected for each field. - -### General error messages - -Now let's suppose you want to have a general error message for the "required", "email" and "maxlength" rules in the "Email" field. - -You can use the rule positions to specify a common error message. Here's how you can do it: - -```html - -``` - -Avec cette configuration, Trivule affichera le message d'erreur "**Veuillez saisir une adresse email valide**" si le champ est vide, n'est pas une adresse valide ou dépasse 32 caractères. - -### Message placement - -Suppose you want to display error messages in specific locations on your page, rather than just next to the form fields. - -You can use the `data-tr-feedback` attribute to specify where to display the error messages. Here's how you can do it: - -```html - - -
-``` - -With this configuration, the error message will be displayed inside the `
` element with the `data-tr-feedback="name"` attribute. You can place the `
` element anywhere on the page. Trivule will display the error message in the nearest element to the corresponding input. - -This allows you to control the location where error messages are displayed on the page and style them according to your needs. You can use CSS selectors to target elements with the `data-tr-feedback` attribute and apply specific styles to the error messages. For example: - -```css -div[data-tr-feedback] { - color: red; - font-size: 14px; -} -``` -### Ways to display error messages: -Trivule provides different ways to display errors in a form. - -#### Via HTML: -If you want to display all error messages once the first rule fails, you can use the `data-tr-show` attribute. It accepts two possible values: `first` and `full`. - -```html - -``` - -By default, the value is set to `first`, which means only the first error message will be displayed. If you choose the value `full`, all error messages from all the rules will be displayed. - -#### Via JavaScript: -When using JavaScript, you can set the `failsOnfirst` option to `true`. In this case, as soon as the first rule fails, the validation will stop, and the error message for that rule will be displayed. - -```javascript -const trInput = new TrInput("#my-input", { - failsOnfirst: true, -}); -``` - -When `failsOnfirst` is set to `false`, all the rules will be executed, and all error messages will be displayed. - -These options provide flexibility in controlling how error messages are displayed based on your specific requirements. - -## Advanced customization - -### Interacting with Input During Validation - -The `onFails` and `onPasses` methods of the `TrInput` class allow you to interact with the `input` element when validation fails or succeeds for a given form field. - -The `onFails` method sets an event listener that will be triggered when validation fails. Here's an example of usage: - -```javascript -import TrInput from 'Trivule'; - -const trInput = new TrInput("#my-input"); -//Initialize before anything -trInput.init(); - -trInput.onFails(() => { - // Code to execute when validation fails - console.log("Validation failed!"); -}); -``` - -In this example, a callback function is defined to display a message in the console when validation fails. You can customize the code to execute based on your needs, such as displaying an error message to the user or applying specific styles to the `input` element. - -Similarly, the `onPasses` method allows you to set an event listener that will be triggered when validation succeeds. Here's an example of usage: - -```javascript -trInput.onPasses(() => { - // Code to execute when validation succeeds - console.log("Validation succeeded!"); -}); -``` - -In this example, a callback function is defined to display a message in the console when validation succeeds. You can modify the code to execute based on your needs, such as validating other form fields or enabling a submission button. - -By using these methods, you can react to successful or failed validation events and perform specific actions accordingly. This allows you to add custom logic to your application based on the result of form field validation. - -### Emitting Custom Events - -The `emit` method of the `TrInput` class allows you to emit a custom event to the associated `input` element. Here's an example of usage: - -```javascript -trInput.emit("myEvent", { data: "Custom value" }); -``` - -In this example, a custom event named "myEvent" is emitted to the `input` element. Additional data `{ data: "Custom value" }` can be passed along with the event. - -You can use this feature to create advanced communication and interaction between your application and the `TrInput` class. For example, you can emit a custom event when the value of the `input` element changes and listen to that event to perform specific actions in other parts of your application. - -### Attaching Event Listeners - -The `on` method of the `TrInput` class allows you to attach an event listener to the associated `input` element. Here's an example of usage: - -```javascript -trInput.on("change", (event) => { - // Code to execute when "change" event occurs - console.log("Value has changed:", event.target.value); -}); -``` - -In this example, an event listener is attached to the `input` element for the "change" event. When this event occurs, the callback function is executed, displaying the new value of the `input` element in the console. You can listen to other events such as "input" or "blur" by specifying the corresponding event name. - -This allows you to listen to specific events emitted by the `input` element and perform custom actions in response to those events. For example, you can detect value changes in the `input` element or loss of focus and perform actions accordingly, such as updating other elements in the user interface or performing asynchronous data validation. - -### Validating the Input Element - -The `valid` method of the `TrInput` class allows you to perform validation on the `input` element using the defined validation rules. Here's an example of usage: - -```javascript -const isValid = trInput.valid(); -if (isValid) { - // Proceed with form submission or handle valid input -} else { - // Display error messages or handle invalid - - input -} -``` - -In this example, the `valid` method is called to validate the `input` element. The return value `isValid` indicates whether the element is valid or not. You can use this information to make decisions in your code, such as submitting the form or displaying error messages to the user. - -The `valid` method updates the `_passed` property of the `TrInput` instance with the validation result and returns that result. It performs the validation using the current value of the `input` element and the defined validation rules. - -### Validating and Emitting Validation Events - -The `validate` method of the `TrInput` class performs validation on the `input` element using the defined validation rules. It also emits the "tr.input.passes" or "tr.input.fails" events based on the validation result. Here's an example of usage: - -```javascript -const isValid = trInput.validate(); -if (isValid) { - // Proceed with form submission or handle valid input -} else { - // Display error messages or handle invalid input -} -``` - -In this example, the `validate` method is called to validate the `input` element. The return value `isValid` indicates whether the element is valid or not. You can use this information to make decisions in your code, such as submitting the form or displaying error messages to the user. - -The `validate` method performs the following steps: - -1. It calls the `valid` method to perform validation on the `input` element and update the `_passed` property with the result. -2. It calls other methods to update CSS classes, retrieve error messages, and emit validation events. -3. It returns the value of the validation result (`this._passed`). - -You can use the `validate` method when you want to perform a full validation of the `input` element, update the user interface based on the validation result, and emit the corresponding events. - -### Listening to Validation Events - -When validation fails or passes, the `tr.input.fails` and `tr.input.passes` events are emitted for you to interact with Trivule in your code. - -```js -const myInput = document.getElementBy('my-input'); -myInput.addEventListener('tr.input.passes', (e) => { - console.log(e.detail); - // Your code -}); -``` - -### Destroying the TrInput Instance - -The `destroy` method of the `TrInput` class allows you to reset the `TrInput` instance by removing the validation rules and associated event listeners. Here's an example of usage: - -```javascript -trInput.destroy(); -``` - -In this example, the `destroy` method is called on the `trInput` instance. This removes all custom validation rules and event listeners associated with that instance. - -You can use the `destroy` method when you want to reset the `TrInput` instance to its initial state, such as when removing or disabling a form field. - -By using the methods and events provided by the `TrInput` class, you can customize form field validation and interaction in your application. Whether it's reacting to successful or failed validation events, emitting custom events, listening to `input` element events, or performing specific validations, you have the ability to add custom logic to your form-based application based on the validation results of the form fields. \ No newline at end of file diff --git a/docs/validation/trivule.md b/docs/validation/trivule.md deleted file mode 100644 index 225fcd7..0000000 --- a/docs/validation/trivule.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -sidebar_position: 14 -title: Global Validation ---- - -# Global Validation - -## Trivule - -If you have a website or application and want to apply the same validation rules to all forms without managing each form individually, you can use global validation. - -## Usage - -To set up global validation, simply initialize Trivule: - -```html - -``` - -This activates global validation for all your forms. \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 1a19f55..d17db04 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "trivule-docs", - "version": "0.0.0", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "trivule-docs", - "version": "0.0.0", + "version": "1.0.0", "dependencies": { "@docusaurus/core": "^3.2.1", "@docusaurus/preset-classic": "^3.2.1", diff --git a/static/img/example.png b/static/img/example.png index 62799d3..f2f42b8 100644 Binary files a/static/img/example.png and b/static/img/example.png differ diff --git a/todo.md b/todo.md index 8a20cc2..4bf58d9 100644 --- a/todo.md +++ b/todo.md @@ -1,2 +1,3 @@ - Rewrite onInit doc (docs/validation/tr-form) -- Rewrite the doc of size rule \ No newline at end of file +- Rewrite the doc of size rule +- Write doc for imperative mode