promise validator

Use Promise to validate value

Options

Using with form field
The HTML attributes are used to set the validator options via the Declarative plugin
(* denotes a required option)
NameHTML attributeTypeDescription
messagedata-fv-promise___messageStringThe error message
promise *data-fv-promise___promiseString or FunctionThe callback returns promise instance
The promise option must be a function or the name of function which returns a Promise as following:
promise: function(input) {
// input.value is the value of field
// input.element is the field element
return new Promise(function(resolve, reject) {
// Do something ...
// Resolve when particular task is done
resolve({
valid: true, // or false, // Required
message: 'Other message', // Optional
// You can attach more data to reuse later
meta: {
key: value
},
});
// You can reject if there is error
reject({
valid: false, // Required
message: 'Other message', // Optional
// You can attach more data to reuse later
meta: {
key: value
},
});
});
}

Basic example

The following form asks user to upload an avatar which both width and height must be less than 300px.
Use the file validator if you want to validate size of an image
They can be determined using Promise as seen in the following snippet:
promise: function(input) {
return new Promise(function(resolve, reject) {
const files = input.element.files
if (!files.length || typeof FileReader === 'undefined') {
resolve({
valid: true,
});
}
const img = new Image();
img.addEventListener('load', function() {
const w = this.width;
const h = this.height;
resolve({
valid: (w <= 300 && h <= 300),
message: 'The avatar width and height must be less than 300 px',
meta: {
// We will use it later to show the preview
source: img.src,
width: w,
height: h,
},
});
});
img.addEventListener('error', function() {
reject({
valid: false,
message: 'Please choose an image',
});
});
const reader = new FileReader();
reader.readAsDataURL(files[0]);
reader.addEventListener('loadend', function(e) {
img.src = e.target.result;
});
});
}
When the field is validated completely, we can get the custom data stored in the result's meta:
formValidationInstance.on('core.validator.validated', function(e) {
if (e.field === 'avatar' && e.validator === 'promise') {
if (e.result.valid && e.result.meta && e.result.meta.source) {
// Get the source of selected image
const source = e.result.meta.source;
// Display the avatar in the preview area
...
} else if (!e.result.valid) {
// Remove the preview
...
}
}
});
promise validator

See also

Changelog

v2.0.0
  • Add the npm package