After developing a validator to ensure that a digit is a number and restricts it to having 2 digits after the decimal place, I realized that it does not account for two specific scenarios: a 6-digit number with no decimal places (e.g. 123456) or an 8-digit number with 2 decimal places (e.g. 123456.78). Below is the code that addresses this concern:
function validateInt2Dec(value, min, max) {
if (Math.sign(value) === -1) {
var negativeValue = true;
value = -value
}
if (!value) {
return true;
}
var format = /^\d+\.?\d{0,2}$/.test(value);
if (format) {
if (value < min || value > max) {
format = false;
}
}
return format;
}
This function can be implemented in a formly form as shown below:
vm.fields = [
{
className: 'row',
fieldGroup: [
{
className: 'col-xs-6',
key: 'payment',
type: 'input',
templateOptions: {
label: 'Payment',
required: false,
maxlength: 8
},
validators: {
cost: function(viewValue, modelValue, scope) {
var value = modelValue || viewValue;
return validateInt2Dec(value);
}
}
}
]
}
];
To accommodate the aforementioned scenarios, additional conditions need to be added to the validator function.