### Install JustValidate with NPM Source: https://just-validate.dev Install the JustValidate library using the NPM package manager. ```bash npm install just-validate --save ``` -------------------------------- ### Install JustValidate with Yarn Source: https://just-validate.dev Install the JustValidate library using the Yarn package manager. ```bash yarn add just-validate ``` -------------------------------- ### Complete Form and Validation Setup Source: https://just-validate.dev/docs/tutorial/files-validation Sets up a form with multiple file input fields and applies various validation rules including file count and attributes. ```html
``` ```javascript const validator = new JustValidate('#files_form'); validator .addField('#files_minmax', [ { rule: 'minFilesCount', value: 1, }, { rule: 'maxFilesCount', value: 3, }, ]) .addField('#files_png', [ { rule: 'minFilesCount', value: 1, }, { rule: 'maxFilesCount', value: 1, }, { rule: 'files', value: { files: { types: ['image/png'], extensions: ['png'], }, }, }, ]) .addField('#files_attr', [ { rule: 'minFilesCount', value: 1, }, { rule: 'files', value: { files: { extensions: ['jpeg', 'jpg', 'png'], maxSize: 20000, minSize: 10000, types: ['image/jpeg', 'image/jpg', 'image/png'], }, }, }, ]); ``` -------------------------------- ### Initialize JustValidate without Bundlers Source: https://just-validate.dev/docs/intro Initialize JustValidate using the global `window.JustValidate` object after including it from a CDN. This is used in traditional HTML setups. ```javascript const validate = new window.JustValidate('#form'); ``` -------------------------------- ### Advanced Form Validation Setup Source: https://just-validate.dev/docs/intro Initialize JustValidate for a form and add various fields with different validation rules. Includes required fields, custom validators, and specific rule types like numbers and integers. ```javascript const validator = new JustValidate('#advanced-usage_form'); validator .addField('#advanced-usage_password', [ { rule: 'required', }, ]) .addField('#advanced-usage_repeat-password', [ { rule: 'required', }, { validator: (value, fields) => { if ( fields['#advanced-usage_password'] && fields['#advanced-usage_password'].elem ) { const repeatPasswordValue = fields['#advanced-usage_password'].elem.value; return value === repeatPasswordValue; } return true; }, errorMessage: 'Passwords should be the same', }, ]) .addField('#advanced-usage_message', [ { validator: (value) => { return value !== undefined && (value as string).length > 3; }, errorMessage: 'Message should be more than 3 letters.', }, ]) .addField( '#advanced-usage_consent_checkbox', [ { rule: 'required', }, ], { errorsContainer: '#advanced-usage_consent_checkbox-errors-container', } ) .addField('#advanced-usage_favorite_animal_select', [ { rule: 'required', }, ]) .addRequiredGroup( '#advanced-usage_communication_checkbox_group', 'You should select at least one communication channel' ) .addRequiredGroup('#advanced-usage_communication_radio_group') .addField('#advanced-usage_input_number', [ { rule: 'required', }, { rule: 'number', }, ]) .addField('#advanced-usage_input_integer_number', [ { rule: 'required', }, { rule: 'integer', }, ]) .addField('#advanced-usage_input_number_between', [ { rule: 'required', }, { rule: 'minNumber', value: 10, }, { rule: 'maxNumber', value: 20, }, ]); ``` -------------------------------- ### Localizing Error Messages with JustValidate Source: https://just-validate.dev/docs/tutorial/localization Configure custom error messages for different languages by providing a dictionary of translations. This example sets up validation rules for name and email fields and defines Spanish and French translations for common error keys. ```javascript import JustValidate from 'just-validate'; const validator = new JustValidate('#localisation_form', undefined, [ { key: 'Name is required', dict: { Spanish: 'Se requiere el nombre', French: 'Le nom est requis', }, }, { key: 'Name is too short', dict: { Spanish: 'El nombre es muy corto', French: 'Le nom est trop court', }, }, { key: 'Name is too long', dict: { Spanish: 'El nombre es demasiado largo', French: 'Le nom est trop long', }, }, { key: 'Email is required', dict: { Spanish: 'Correo electronico es requerido', French: "L'e-mail est requis", }, }, { key: 'Email is invalid', dict: { Spanish: 'El correo electrónico es invalido', French: 'Le courriel est invalide', }, }, ]); validator .addField('#localisation_form_name', [ { rule: 'required', errorMessage: 'Name is required', }, { rule: 'minLength', value: 3, errorMessage: 'Name is too short', }, { rule: 'maxLength', value: 15, errorMessage: 'Name is too long', }, ]) .addField('#localisation_form_email', [ { rule: 'required', errorMessage: 'Email is required', }, { rule: 'email', errorMessage: 'Email is invalid', }, ]); validator.setCurrentLocale('English'); ``` -------------------------------- ### Custom Error Label Style Example Source: https://just-validate.dev/docs/instance/errorLabelStyle Apply custom CSS styles to error labels by providing a `Partial` object to the `errorLabelStyle` option. This example sets the background color to red. ```javascript { errorLabelStyle: { backgroundColor: 'red'; } } ``` -------------------------------- ### Custom Async Validation Rule Source: https://just-validate.dev Implement a custom asynchronous validation rule using a validator function that returns a Promise. This example checks if an email already exists. ```javascript validator .addField('#async_email', [ { rule: 'required', }, { validator: () => () => new Promise((resolve) => { setTimeout(() => { resolve(false); }, 1000); }), errorMessage: 'Email already exists!', }, ]) ``` -------------------------------- ### Date Validation Plugin Source: https://just-validate.dev Utilize the JustValidatePluginDate plugin to enforce a specific date format for input fields. This example requires the date to be in dd/MM/yyyy format. ```javascript validator .addField('#date-text_start_date', [ { rule: 'required', }, { plugin: JustValidatePluginDate(() => ({ format: 'dd/MM/yyyy', })), errorMessage: 'Date should be in dd/MM/yyyy format (e.g. 20/12/2021)', }, ]) ``` -------------------------------- ### Set Custom Error Label CSS Class Source: https://just-validate.dev/docs/instance/errorLabelCssClass Configure the CSS class to be applied to invalid labels. This example shows how to set a custom class 'invalid'. ```javascript { errorLabelCssClass: ['invalid'], } ``` -------------------------------- ### Validate Date Range Between Fields Source: https://just-validate.dev/docs/tutorial/date-validation Validates a date field to be between the values of other date fields. This is useful for date ranges where the start and end dates are user-defined. ```javascript import JustValidatePluginDate from 'just-validate-plugin-date'; validation .addField('#date-start', [ { plugin: JustValidatePluginDate(() => ({ format: 'dd/MM/yyyy', })), errorMessage: 'Date should be in dd/MM/yyyy format (e.g. 15/10/2021)', }, ]) .addField('#date-between', [ { plugin: JustValidatePluginDate(() => ({ format: 'dd/MM/yyyy', })), errorMessage: 'Date should be in dd/MM/yyyy format (e.g. 15/10/2021)', }, { plugin: JustValidatePluginDate((fields) => ({ format: 'dd/MM/yyyy', isAfter: fields['#date-start'].elem.value, isBefore: fields['#date-end'].elem.value, })), errorMessage: 'Date should be between start and end dates', }, ]) .addField('#date-between-required', [ { plugin: JustValidatePluginDate(() => ({ required: true, format: 'dd/MM/yyyy', })), errorMessage: 'Date should be in dd/MM/yyyy format (e.g. 15/10/2021)', }, { plugin: JustValidatePluginDate((fields) => ({ required: true, format: 'dd/MM/yyyy', isAfter: fields['#date-start'].elem.value, isBefore: fields['#date-end'].elem.value, })), errorMessage: 'Date should be between start and end dates', }, ]) .addField('#date-end', [ { plugin: JustValidatePluginDate(() => ({ format: 'dd/MM/yyyy', })), errorMessage: 'Date should be in dd/MM/yyyy format (e.g. 15/10/2021)', }, ]); ``` -------------------------------- ### JustValidate Constructor with Global Config Source: https://just-validate.dev/docs/instance Instantiate JustValidate with global configuration options that apply to all fields. Customize error styles, CSS classes, tooltip behavior, and more. This is useful for setting up a consistent validation experience across your entire form. ```typescript new JustValidate( form: string | Element, globalConfig?: { errorFieldStyle: Partial, errorFieldCssClass: string | string[], errorLabelStyle: Partial, errorLabelCssClass: string | string[], lockForm: boolean, testingMode: boolean, validateBeforeSubmitting: boolean, focusInvalidField?: boolean, tooltip?: { position: 'left' | 'top' | 'right' | 'bottom', }, errorsContainer?: string | Element, }, dictLocale?: { key: string; dict: { [localeKey: string]: string, }; }[]; ); ``` -------------------------------- ### HTML Form for Localization Demo Source: https://just-validate.dev/docs/tutorial/localization This HTML structure sets up a form with input fields for name and email, and a select dropdown to choose the error message language. It includes basic form elements and a submit button. ```html
``` -------------------------------- ### Show Success Labels with Key-Message Pairs Source: https://just-validate.dev/docs/methods/showSuccessLabels Use this method to manually display success messages for specific input fields. Provide an object where keys are CSS selectors for the input fields and values are the success messages. ```javascript .showSuccessLabels(labels: {key: message}) ``` ```javascript .showSuccessLabels({ '#email': 'The email looks good!' }) ``` -------------------------------- ### Validate File Attributes Source: https://just-validate.dev/docs/tutorial/files-validation Set validation rules for file extensions, types, minimum size, maximum size, and specific filenames. Sizes should be in bytes. ```javascript validation.addField('#file', [ { rule: 'file', value: { files: { extensions: ['jpeg', 'png'], maxSize: 25000, minSize: 1000, types: ['image/jpeg', 'image/png'], names: ['file1.jpeg', 'file2.png'], }, }, }, ]); ``` -------------------------------- ### showSuccessLabels Source: https://just-validate.dev/docs/category/methods Manually displays success indicators or labels for the form. ```APIDOC ## showSuccessLabels ### Description Method to show success labels manually. ### Method Instance Method ``` -------------------------------- ### Date Validation Plugin Configuration Source: https://just-validate.dev/docs/tutorial/date-validation Defines the configuration options for the JustValidatePluginDate. Use this to set required fields, date formats, and date range constraints. ```javascript JustValidatePluginDate((fields) => ({ required: boolean, format: string, isBefore: Date | string, isAfter: Date | string, isBeforeOrEqual: Date | string, isAfterOrEqual: Date | string, isEqual: Date | string, })); ``` -------------------------------- ### Define Validation Rules using Selectors Source: https://just-validate.dev/docs/intro Initialize JustValidate with a form selector and define validation rules for individual fields using their selectors and rule configurations. ```javascript const validator = new JustValidate('#basic_form'); validator .addField('#basic_name', [ { rule: 'required', }, { rule: 'minLength', value: 3, }, { rule: 'maxLength', value: 15, }, ]) .addField('#basic_email', [ { rule: 'required', }, { rule: 'required', }, { rule: 'email', }, ]) .addField('#basic_password', [ { rule: 'required', }, { rule: 'password', }, ]) .addField('#basic_age', [ { rule: 'required', }, { rule: 'number', }, { rule: 'minNumber', value: 18, }, { rule: 'maxNumber', value: 150, }, ]); ``` -------------------------------- ### Import JustValidate with Code Bundlers Source: https://just-validate.dev/docs/intro Import and initialize JustValidate as a module when using JavaScript bundlers like Webpack or Rollup. ```javascript import JustValidate from 'just-validate'; const validate = new JustValidate('#form'); ``` -------------------------------- ### Configure Tooltip Position Source: https://just-validate.dev/docs/instance/tooltip Define tooltip behavior by specifying its position. Supported positions are 'left', 'top', 'right', and 'bottom'. ```javascript { tooltip: { position: 'top', }, } ``` -------------------------------- ### Enable Testing Mode Source: https://just-validate.dev/docs/instance/testingMode Set `testingMode` to `true` in the configuration object to enable the addition of `data-testid` attributes. ```javascript { testingMode: true, } ``` -------------------------------- ### Import JustValidate as a Module Source: https://just-validate.dev Import the JustValidate library as a module in your JavaScript or TypeScript project. ```javascript import JustValidate from 'just-validate'; ``` -------------------------------- ### Add File Validation Rule Source: https://just-validate.dev/docs/rules/files Use the 'files' rule to validate uploaded files. Configure allowed extensions, min/max size, and MIME types. ```javascript const validator = new JustValidate('#form'); validator.addField('#files', [ { rule: 'files', value: { files: { extensions: ['jpeg', 'jpg', 'png'], maxSize: 20000, minSize: 10000, types: ['image/jpeg', 'image/jpg', 'image/png'], }, }, }, ]); ``` -------------------------------- ### File Attribute Configuration Object Source: https://just-validate.dev/docs/tutorial/files-validation Defines the structure for specifying file attributes like extensions, types, and size limits within the validation rules. ```javascript { files: { extensions?: string[], types?: string[], minSize?: number, maxSize?: number, names?: string[], } } ``` -------------------------------- ### Access JustValidate Globally Source: https://just-validate.dev Access the JustValidate library globally via the window object after including it via CDN. ```javascript window.JustValidate ``` -------------------------------- ### Add minFilesCount Rule to File Input Source: https://just-validate.dev/docs/rules/minFilesCount Use the minFilesCount rule to enforce a minimum number of uploaded files. Set the 'value' to the required minimum count. ```javascript const validator = new JustValidate('#form'); validator.addField('#files', [ { rule: 'minFilesCount', value: 2, }, ]); ``` -------------------------------- ### successLabelStyle Configuration Source: https://just-validate.dev/docs/instance/successLabelStyle Allows for the application of custom CSS styles to a label when its associated input is valid. This property accepts an object conforming to `Partial`. ```APIDOC ## successLabelStyle Custom CSS styles for valid label. ### Type `Partial` ### Value by default `undefined` ### Example ```json { "successLabelStyle": { "backgroundColor": "green" } } ``` ``` -------------------------------- ### Configure Success Label Style Source: https://just-validate.dev/docs/instance/successLabelStyle Set custom CSS properties for the label when validation passes. This option accepts a partial CSS declaration object. ```javascript { successLabelStyle: { backgroundColor: 'green'; } } ``` -------------------------------- ### Define Validation Rules using DOM Elements Source: https://just-validate.dev/docs/intro Initialize JustValidate with a form DOM element and define validation rules for fields using their respective DOM elements and rule configurations. ```javascript const validator = new JustValidate(document.querySelector('#basic_form')); validator .addField(document.querySelector('#basic_name'), [ { rule: 'required', }, { rule: 'minLength', value: 3, }, { rule: 'maxLength', value: 15, }, ]) .addField(document.querySelector('#basic_email'), [ { rule: 'required', }, { rule: 'email', }, ]) .addField(document.querySelector('#basic_password'), [ { rule: 'required', }, { rule: 'password', }, ]) .addField(document.querySelector('#basic_age'), [ { rule: 'required', }, { rule: 'number', }, { rule: 'minNumber', value: 18, }, { rule: 'maxNumber', value: 150, }, ]); ``` -------------------------------- ### Validate File Count Source: https://just-validate.dev/docs/tutorial/files-validation Configure validation rules for the minimum and maximum number of files allowed. Ensure the input element has the 'multiple' attribute. ```javascript validation.addField('#file', [ { rule: 'minFilesCount', value: 1, }, { rule: 'maxFilesCount', value: 3, }, ]); ``` -------------------------------- ### Basic Form Validation Rules Source: https://just-validate.dev Configure basic validation rules such as required, minLength, maxLength, email, password, and number for form fields. ```javascript validator .addField(document.querySelector('#basic_name'), [ { rule: 'required', }, { rule: 'minLength', value: 3, }, { rule: 'maxLength', value: 15, }, ]) .addField(document.querySelector('#basic_email'), [ { rule: 'required', }, { rule: 'email', }, ]) .addField(document.querySelector('#basic_password'), [ { rule: 'required', }, { rule: 'password', }, ]) .addField(document.querySelector('#basic_age'), [ { rule: 'required', }, { rule: 'number', }, { rule: 'minNumber', value: 18, }, { rule: 'maxNumber', value: 150, }, ]); ``` -------------------------------- ### onFail Source: https://just-validate.dev/docs/category/methods Sets a callback function to be executed when the validation fails. ```APIDOC ## onFail ### Description Callback if validation failed. ### Method Instance Method ``` -------------------------------- ### onSuccess Source: https://just-validate.dev/docs/category/methods Sets a callback function to be executed when the validation passes successfully. ```APIDOC ## onSuccess ### Description Callback if validation passed. ### Method Instance Method ``` -------------------------------- ### HTML Input for File Upload Source: https://just-validate.dev/docs/tutorial/files-validation Basic HTML input element for file uploads. Use the 'multiple' attribute to allow multiple file selections. ```html ``` ```html ``` -------------------------------- ### Basic HTML Form Structure Source: https://just-validate.dev/docs/intro A simple HTML form structure that can be used with JustValidate for client-side validation. ```html
``` -------------------------------- ### Include JustValidate via CDN Source: https://just-validate.dev Include the JustValidate script directly in your HTML file using a CDN link. ```html ``` -------------------------------- ### successFieldStyle Configuration Source: https://just-validate.dev/docs/instance/successFieldStyle Defines custom CSS styles to be applied to a form field when it is considered valid. This allows for visual feedback to the user upon successful validation. ```APIDOC ## successFieldStyle Custom CSS styles for valid field. ### Type `Partial` ### Value by default `undefined` ### Example ```json { "successFieldStyle": { "backgroundColor": "green" } } ``` ``` -------------------------------- ### Rule Object with Value Source: https://just-validate.dev/docs/tutorial/rule-object Specify a value for rules that require a comparison, like 'minLength' or 'minNumber'. ```javascript [ { rule: 'minLength', value: 3, }, { rule: 'maxLength', value: 15, }, ] ``` -------------------------------- ### Basic Rule Object Source: https://just-validate.dev/docs/tutorial/rule-object Use this object to define a simple validation rule, such as 'required'. ```javascript { rule: 'required', } ``` -------------------------------- ### Limit Uploaded Files Count Source: https://just-validate.dev/docs/rules/maxFilesCount Use the maxFilesCount rule to restrict the number of files that can be uploaded. Configure the maximum allowed files by setting the 'value' property. ```javascript const validator = new JustValidate('#form'); validator.addField('#files', [ { rule: 'maxFilesCount', value: 2, }, ]); ``` -------------------------------- ### Set Custom Success Field CSS Classes Source: https://just-validate.dev/docs/instance/successFieldCssClass Provide an array of strings to define custom CSS classes for successfully validated fields. This allows for more specific styling of valid inputs. ```javascript { successFieldCssClass: ['valid'], } ``` -------------------------------- ### Change Current Locale Source: https://just-validate.dev/docs/methods/setCurrentLocale Call this method to set the application's locale. Pass a string representing the desired locale (e.g., 'es' for Spanish). ```javascript .setCurrentLocale('es') ``` -------------------------------- ### Apply Custom Styles to Valid Fields Source: https://just-validate.dev/docs/instance/successFieldStyle Use successFieldStyle to define inline CSS properties for fields that are valid. This allows for visual feedback on successful validation. ```javascript { successFieldStyle: { backgroundColor: 'green'; } } ``` -------------------------------- ### showErrors Source: https://just-validate.dev/docs/category/methods Manually displays error messages for the form. ```APIDOC ## showErrors ### Description Method to show errors manually. ### Method Instance Method ``` -------------------------------- ### Add Custom Regexp Rule to Field Source: https://just-validate.dev/docs/rules/customRegexp Use the customRegexp rule to validate a field against a specific regular expression. Ensure the regular expression is correctly defined. ```javascript const validator = new JustValidate('#form'); validator.addField('#regexp', [ { rule: 'customRegexp', value: /[a-z]/gi, }, ]); ``` -------------------------------- ### Manually Submitting Form in onSuccess Source: https://just-validate.dev/docs/methods/onSuccess Use the onSuccess callback to manually submit the form after validation passes. This is an alternative to using the submitFormAutomatically setting. ```javascript .onSuccess(( event ) => { event.currentTarget.submit(); }); ``` -------------------------------- ### Configure validateBeforeSubmitting Source: https://just-validate.dev/docs/instance/validateBeforeSubmitting Set this option to false to disable pre-submission validation for a field. The default value is false. ```javascript { validateBeforeSubmitting: false, } ``` -------------------------------- ### Set Custom Success Label CSS Class Source: https://just-validate.dev/docs/instance/successLabelCssClass Configure the `successLabelCssClass` option to specify custom CSS classes for valid labels. This allows for distinct styling of valid input states. ```javascript { successLabelCssClass: ['valid'], } ``` -------------------------------- ### onValidate Source: https://just-validate.dev/docs/category/methods Sets a callback function to be triggered after every validation run. ```APIDOC ## onValidate ### Description Callback triggered after every validation run. ### Method Instance Method ``` -------------------------------- ### showErrors Method Source: https://just-validate.dev/docs/methods/showErrors Manually displays validation errors. Accepts an object where keys are selectors or field names and values are the error messages. ```APIDOC ## showErrors ### Description Method to show errors manually. ### Method Signature `.showErrors(errors: {key: message})` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **errors** (object) - Required - An object where keys represent the identifier of the field or element to display the error for (e.g., a CSS selector or field name), and values are the corresponding error messages (strings). ### Request Example ```javascript .showErrors({ '#email': 'The email is invalid' }) ``` ### Response This method does not return a value. It triggers a UI update to display errors. ``` -------------------------------- ### addField Source: https://just-validate.dev/docs/category/methods Defines validation rules for a new field to be added to the form. ```APIDOC ## addField ### Description Defines validation rules for the new field. ### Method Instance Method ``` -------------------------------- ### onValidate Source: https://just-validate.dev/docs/methods/onValidate This callback is invoked after every validation process. It receives an object containing the validation status, submission status, and details about fields and groups. Note that `isValid` might be undefined if the callback is used before form submission without explicitly enabling `validateBeforeSubmitting`. ```APIDOC ## onValidate ### Description Callback triggered after every validation run. ### Parameters - **isValid** (boolean | undefined) - Indicates if the form is currently valid. May be undefined before submission if `validateBeforeSubmitting` is not enabled. - **isSubmitted** (boolean) - Indicates if the form has been submitted. - **fields** (object) - An object containing the validation status and values for each field. - **groups** (object) - An object containing the validation status for field groups. ``` -------------------------------- ### Validate Date Range (isBefore/isAfter) Source: https://just-validate.dev/docs/tutorial/date-validation Validates if a date falls within a specified range using 'isBefore' and 'isAfter'. It's crucial that the 'format' option matches the format used in 'isBefore' and 'isAfter' for correct parsing. ```javascript import JustValidatePluginDate from 'just-validate-plugin-date'; validation.addField('#date', [ { plugin: JustValidatePluginDate(() => ({ format: 'dd/MM/yyyy', isBefore: '15/12/2021', isAfter: '10/12/2021', })), errorMessage: 'Date should be between 10/12/2021 and 15/12/2021', }, ]); ``` -------------------------------- ### Enable Automatic Form Submission Source: https://just-validate.dev/docs/instance/submitFormAutomatically Set this option to true to automatically submit the form after successful validation. The default value is false. ```javascript { submitFormAutomatically: true, } ``` -------------------------------- ### Rule Object with Synchronous Custom Validator Source: https://just-validate.dev/docs/tutorial/rule-object Implement custom synchronous validation logic using a validator function that returns true or false. ```javascript { validator: (value, context) => value === '20' ? false : true, } ``` -------------------------------- ### Add Strong Password Rule to Field Source: https://just-validate.dev/docs/rules/strongPassword Use this snippet to apply the strongPassword rule to a form field. Remember to add the 'required' rule if the field must not be empty. ```javascript const validator = new JustValidate('#form'); validator.addField('#password', [ { rule: 'strongPassword', }, ]); ``` -------------------------------- ### Define Custom Translations Source: https://just-validate.dev/docs/tutorial/localization Define a `dictLocale` array to specify translations for different languages. Each object in the array should have a `key` for the default message and a `dict` object containing language-specific translations. ```javascript [ { key: 'Name is required', dict: { Spanish: 'Se requiere el nombre', French: 'Le nom est requis', }, }, { key: 'Name is too short', dict: { Spanish: 'El nombre es muy corto', French: 'Le nom est trop court', }, }, { key: 'Name is too long', dict: { Spanish: 'El nombre es demasiado largo', French: 'Le nom est trop long', }, }, { key: 'Email is required', dict: { Spanish: 'Correo electronico es requerido', French: "L'e-mail est requis", }, }, { key: 'Email is invalid', dict: { Spanish: 'El correo electrónico es invalido', French: 'Le courriel est invalide', }, }, ]; ``` -------------------------------- ### addField Method Signature Source: https://just-validate.dev/docs/methods/addField Defines validation rules for a new field. The method returns a JustValidate instance, allowing for chained calls. ```APIDOC ## addField(field, rules, config) ### Description Adds a field to the validation instance and applies specified rules and configuration. ### Parameters - **field** (string | DOMElement) - Required - A string selector or DOM element representing the form field. - **rules** (Array) - Required - An array of validation rule objects. - **config** (Object) - Optional - Specific settings applied to this field, overriding default configurations. ### Config Options - **errorFieldCssClass** (string) - Overrides the CSS class for error fields. - **errorFieldStyle** (Object) - Overrides the CSS style for error fields. - **errorLabelCssClass** (string) - Overrides the CSS class for error labels. - **errorLabelStyle** (Object) - Overrides the CSS style for error labels. - **successFieldCssClass** (string) - Overrides the CSS class for success fields. - **successFieldStyle** (Object) - Overrides the CSS style for success fields. - **successLabelCssClass** (string) - Overrides the CSS class for success labels. - **successLabelStyle** (Object) - Overrides the CSS style for success labels. - **tooltip** (Object) - Overrides tooltip settings. - **errorsContainer** (string | DOMElement) - Overrides the container for error messages. - **successMessage** (string) - Custom text to display when the field is valid. Defaults to `undefined` (no success message shown). ### Example ```javascript const validation = new JustValidate('#form'); validation .addField('#name', [ { rule: 'name' }, { rule: 'minLength', value: 3 }, { rule: 'maxLength', value: 20 }, ]) .addField( '#email', [ { rule: 'required' }, { rule: 'email' }, { validator: (value) => () => new Promise((resolve) => { isEmailExist(value).then((isExist) => { resolve(!isExist); }); }), errorMessage: 'Email already exists!', }, ], { errorsContainer: '.custom-errors-container', successMessage: 'Everything looks good!', } ); ``` ### Example with Cross-Field Validation ```javascript const validation = new JustValidate('#form'); validation.addField('#repeat-password', [ { validator: (value, fields) => { if (fields['#password'] && fields['#password'].elem) { const repeatPasswordValue = fields['#password'].elem.value; return value === repeatPasswordValue; } return true; }, errorMessage: 'Passwords should be the same', }, ]); ``` ``` -------------------------------- ### Switch Current Locale Source: https://just-validate.dev/docs/tutorial/localization Use the `validation.setCurrentLocale()` method to change the active language for validation messages. Pass the language key (e.g., 'es', 'ru') to switch to a specific language, or call it with an empty argument to revert to the default language. ```javascript document.querySelector('#change-lang-btn-en').addEventListener('click', () => { validation.setCurrentLocale(); }); document.querySelector('#change-lang-btn-ru').addEventListener('click', () => { validation.setCurrentLocale('ru'); }); document.querySelector('#change-lang-btn-es').addEventListener('click', () => { validation.setCurrentLocale('es'); }); ``` -------------------------------- ### Adding Fields and Rules with addField Source: https://just-validate.dev/docs/methods/addField Use addField to define validation rules for form elements. It supports chaining and can configure custom error messages, containers, and success messages for individual fields. ```javascript const validation = new JustValidate('#form'); validation .addField('#name', [ { rule: 'name', }, { rule: 'minLength', value: 3, }, { rule: 'maxLength', value: 20, }, ]) .addField( '#email', [ { rule: 'required', }, { rule: 'email', }, { validator: (value) => () => new Promise((resolve) => { isEmailExist(value).then((isExist) => { resolve(!isExist); }); }), errorMessage: 'Email already exists!', }, ], { errorsContainer: '.custom-errors-container', successMessage: 'Everything looks good!', } ); ``` -------------------------------- ### Default Error Field Styles Source: https://just-validate.dev/docs/instance/errorFieldStyle Specifies the default CSS properties applied to invalid fields. This includes text color and border. ```javascript { color: "#b81111", border: "1px solid #B81111" } ``` -------------------------------- ### refresh Source: https://just-validate.dev/docs/category/methods Refreshes the entire form, including field settings, and clears all error messages, styles, and classes. ```APIDOC ## refresh ### Description Method to refresh the whole form - fields settings, clear errors messages/styles/classes. ### Method Instance Method ``` -------------------------------- ### Add Required Group with DOM Element Source: https://just-validate.dev/docs/methods/addRequiredGroup This snippet demonstrates how to use addRequiredGroup by passing a DOM element directly, without specifying a custom error message or configuration. ```javascript const validation = new JustValidate('#form'); validation.addRequiredGroup(document.querySelector('#radio-group')); ``` -------------------------------- ### Refresh the Entire Form Source: https://just-validate.dev/docs/methods/refresh Call this method to reset all fields, clear errors, and remove associated styles and classes. ```javascript .refresh() ``` -------------------------------- ### Rule Object with Custom Error Message Source: https://just-validate.dev/docs/tutorial/rule-object Provide a custom error message string or a function that returns a string for validation failures. ```javascript { errorMessage: 'Invalid field', } ``` -------------------------------- ### onSuccess Callback Signature Source: https://just-validate.dev/docs/methods/onSuccess The onSuccess callback is invoked with the form submit event when validation is successful. ```javascript .onSuccess(event) ``` -------------------------------- ### onValidate Callback Usage Source: https://just-validate.dev/docs/methods/onValidate This callback is triggered after every validation run. Note that `isValid` can be undefined before form submission if `validateBeforeSubmitting` is not configured. ```javascript .onValidate({ isValid, isSubmitted, fields, groups, }) ``` -------------------------------- ### onSuccess Method Source: https://just-validate.dev/docs/methods/onSuccess The onSuccess callback is triggered when the form validation is successful. It receives the form event object. You can use this callback to perform custom actions after successful validation, such as manually submitting the form. ```APIDOC ## onSuccess(event) ### Description Callback invoked when form validation passes. Receives the form submit event. ### Parameters #### Path Parameters - **event** (event) - Required - The form submit event object. ### Notes This callback does not submit the form automatically. Manual submission or `submitFormAutomatically` setting is required. ``` ```APIDOC ## Example Usage ### Description An example demonstrating how to use the onSuccess callback to manually submit the form after validation passes. ### Code ```javascript .onSuccess(( event ) => { event.currentTarget.submit(); }); ``` ``` -------------------------------- ### successFieldCssClass Source: https://just-validate.dev/docs/instance/successFieldCssClass Allows you to specify custom CSS classes to be applied to a field when it is successfully validated. This can be a single string or an array of strings. ```APIDOC ## successFieldCssClass ### Description Custom CSS classes for valid field. ### Type `string | string[]` ### Value by default `just-validate-success-field` ### Example ```json { "successFieldCssClass": ["valid"], } ``` ``` -------------------------------- ### Validate Date Format Source: https://just-validate.dev/docs/tutorial/date-validation Validates that a date input matches a specific format, such as 'dd MMM yyyy'. Ensure the 'format' option matches the expected input. ```javascript import JustValidatePluginDate from 'just-validate-plugin-date'; validation.addField('#date', [ { plugin: JustValidatePluginDate(() => ({ format: 'dd MMM yyyy', })), errorMessage: 'Date should be in dd MMM yyyy format (e.g. 20 Dec 2021)', }, ]); ``` -------------------------------- ### Add Required Group with Custom Error and Config Source: https://just-validate.dev/docs/methods/addRequiredGroup Use this snippet to make a group of fields required, providing a custom error message and specific configuration options for the validation rule. ```javascript const validation = new JustValidate('#form'); validation.addRequiredGroup('#radio-group', 'Select at lease one option!', { successMessage: 'Everything looks good', }); ``` -------------------------------- ### Rule Object with Asynchronous Custom Validator Source: https://just-validate.dev/docs/tutorial/rule-object Define custom asynchronous validation using a validator function that returns a Promise resolving to true or false. ```javascript { validator: (value, context) => () => new Promise((resolve) => { setTimeout(() => { resolve(false); }, 1000); }), } ``` -------------------------------- ### Customizing Error Field Styles Source: https://just-validate.dev/docs/instance/errorFieldStyle Allows overriding or adding custom CSS styles to invalid fields. Use this to change the appearance of validation errors. ```javascript { errorFieldStyle: { backgroundColor: 'red'; } } ``` -------------------------------- ### Set Maximum Text Length with maxLength Source: https://just-validate.dev/docs/rules/maxLength Use the maxLength rule to enforce a maximum character limit on a specific form field. This rule does not trigger an error if the field is empty, so combine it with the 'required' rule if necessary. ```javascript const validator = new JustValidate('#form'); validator.addField('#name', [ { rule: 'maxLength', value: 10, }, ]); ``` -------------------------------- ### Add Integer Validation Rule Source: https://just-validate.dev/docs/rules/integer Use the 'integer' rule to ensure a field accepts only whole numbers. If the field is empty, this rule will not trigger an error. To enforce a value, add the 'required' rule. ```javascript const validator = new JustValidate('#form'); validator.addField('#name', [ { rule: 'integer', }, ]); ``` -------------------------------- ### successLabelCssClass Source: https://just-validate.dev/docs/instance/successLabelCssClass This option allows you to specify a custom CSS class that will be applied to the label element when the associated input field is valid. You can provide a single string or an array of strings for multiple classes. ```APIDOC ## successLabelCssClass ### Description Custom CSS class for valid label. ### Type `string | string[]` ### Value by default `just-validate-success-label` ### Example ```json { "successLabelCssClass": ["valid"], } ``` ```