Magento 2: Data validation message input field
-
06-02-2021 - |
Question
I created an input box in Magento 2 and let the validator check the input value. That works perfect in the example below:
<input id="input-gleich-breite-0"
class="maximum-length-4 validate-digits-range digits-range-200-1440"
name="input-width-0"
type="number"
data-validate="{required:true, 'validate-number':true}"
data-msg-required="Please input data between 200 and 1440"
value="300">
Now I would like to check if the value is in between "200" and "1440". This should work with the following part of input:
data-msg-validate-number="Please input data between 200 and 1440"
But it doesn't work. It only works with the following and only checks for any data in the input box.
data-msg-required="Please input data between 200 and 1440"
The information are taken from here. I really appreciate any hint!
Solution
One thing you could try is to add a JavaScript mixin:
In requirejs-config.js do:
var config = {
config: {
mixins: {
'mage/validation': {
'Vendor_Module/js/validation-mixin': true
}
}
}
}
and Vendor_Module/view/frontend/web/js/validation-mixin.js:
define([
'jquery'
], function ($) {
"use strict";
return function () {
$.validator.addMethod(
'digits-range-200-1440',
function (value) {
// Some custom validation stuff here
return true or false;
},
$.mage.__('Please input data between 200 and 1440')
);
}
});
your input tag
<input id="input-gleich-breite-0"
class="maximum-length-4 validate-digits-range digits-range-200-1440"
name="input-width-0"
type="number"
data-validate="{required:true, 'validate-number':true}"
value="300">
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange