VDF Form Validator JS
npm install @vinzdf89/vdf-form-validator VDFValidator.onValidated(function(form) {
alert('This form has been successfully validated!');
});
Additional callback functions can be defined by simply call again the "onValidated" method.
That's it! This is all you need to do in order to utilize the VDFValidator plugin if you want to import the compiled JS file in the head section of your document.
If you want to utilize the plugin as a JS dependency, useful for example when it has to be imported in projects based on reactive frameworks like Vue, then these are the steps to follow:
first of all, install the dependency as a NPM package:
npm i @vinzdf89/vdf-form-validator
then import it in your js/ts file:
import VDFValidator from '@vinzdf89/vdf-form-validator';
then manually call the following method to initialize the plugin:
VDFValidator.init();
If you are using a framework like Nuxt, and you have also the SSR to handle, then you can avoid the initialization of the plugin on the server by providing a parameter that will stop the execution of the method if its value is falsy. For example:
VDFValidator.init(process.client);
Note: it would be better to call this method when the entire page has been loaded.
Tip: in Vue.js you could create the following composable:
import VDFValidator from '@vinzdf89/vdf-form-validator';
export function useVDFValidator()
{
onMounted(() => {
VDFValidator.init(process.client);
});
return VDFValidator;
}
and then in your .vue file, you can simply call the composable:
const validator = useVDFValidator();
and finally, call the "run" method on the "validator" object returned from the composable once you want to execute the validation.
In the callback that you call once the form has been submitted, you can execute the validation of the form by simply calling the "run" method and passing it the form DOM object as parameter, for example:
const result = await VDFValidator.run(e.target, options);
The second parameter is an optional object and it serves to customize a couple of options:
- autoHandleButtons: it serves if you want to manually handle the disabling of the form's buttons (input[type=submit], button). The default value is "true".
- silent: it serves if you want to silently validate the form. This means that even if the validation fails, you will not see errors. Useful for example if you want to disable the submit button until the fields are valid. The default value is "false".
That said, "result" will contain an object with the details of the validation result, with the following properties:
- data: an object containing the list of fields that failed the validation and the name of the respective validator. This will be an empty object in case the validation is successful
- isValid: booleans true or false, depending on whether the validation has been successful or not
VDFValidator.defineVariable('complexValue', 'This is a complex value example to pass as parameter')
and then add the following class to the input:
Important: when calling resolve or reject, always add a "return" statement to ensure that the execution of the code will stop!
otherwise, the function must just declare the first 2 parameters, and since in this case it is not an asynchronous validation, the function must return a boolean value, true if the validation passes, or false if it fails (instead of the false boolean value, you could also return a string that will be used as custom error message).
With the compact error messages, a span element is added just before the field input's parent node, with the class "verrormsg" and an inline style property to set the color of the text to red.
This first example, shows how to specify an error message for every validation that will fail for the input field named "password".
This second one instead, shows how to provide an error message for a specific validation that fail. In this case the validation is "min" for the input field named "password".
Note: every element containing the custom error message, should be hidden by manually setting the CSS property display to none. In the 2 examples above, this is done by the class "invalid-feedback" from the Bootstrap CSS framework.
Making a select tag as required, be sure that at least one option element has an explicit value attribute set to empty string.
If more than one mode is provided for a single field, then this is the priority that will be followed:
Custom error messages > Compact error messages > In-function error messages
VDFValidator.defineFunction('password', function(field, params) {
const value = field.value.trim();
const minLength = params[0] ?? 6;
const regex = new RegExp((?=.[a-zA-Z]+)(?=.[0-9]+)(?=.*[!$#-])[a-zA-Z0-9!$#-]{${minLength},});
if (!value.length || !regex.test(value)) {
return false; // or you could alternatively return a string to be used as error message
}
return true;
});
As synchronous custom validation, the function must return a boolean value: true for success or false for failure.
VDFValidator.defineFunction('check-username', function(field, params, resolve, reject) {
const userName = params[0] ?? '';
if (!userName.length) {
reject();
}
axios.get('restapi.example.com/user/check-name', {
userName: userName
})
.then(function (response) {
resolve();
})
.catch(function (error) {
reject(); // you could send a string as argument that will be used as error message
});
});
As asynchronous custom validation, the function declares two additional parameters, resolve and reject, to be called (as functions) to respectively end the validation with success or with failure.
You can register one or more callback functions for one or more events:
- onBeforeValidation
- onValidated
- onFailure
- onCompletion
For all of them, you can pass a function as a parameter that will contain the logic to run. This function provides an argument representing the submit event emitted by the form, where the form can be fetched with e.target.
Additional callback functions for the same event, can be defined by simply call the function again.
For example, this is how to register a callback function in case the validation is not successful:
VDFValidator.onFailure(function(e) {
alert('Something went wrong!');
});
For each of the events, you can remove all the defined callback functions for a specific event, by calling the following methods:
- resetOnBeforeValidation
- resetOnValidated
- resetOnFailure
- resetOnCompletion