promise validator
Use Promise to validate value
Options
Using with form field
(* denotes a required option)
Name | HTML attribute | Type | Description |
---|
message | data-fv-promise___message | String | The error message |
promise * | data-fv-promise___promise | String or Function | The 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) {
return new Promise(function(resolve, reject) {
resolve({
valid: true,
message: 'Other message',
meta: {
key: value
},
});
reject({
valid: false,
message: 'Other message',
meta: {
key: value
},
});
});
}
Basic example
The following form asks user to upload an avatar which both width and height must be less than 300px.
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: {
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) {
const source = e.result.meta.source;
...
} else if (!e.result.valid) {
...
}
}
});
See also
Changelog