Reputation: 1937
I've created a validator that checks if digit is a number and makes sure there are 2 digits allowed after a decimal place. What this doesn't cover is a number that is either 6 digits with no decimal places (123456) or 8 digits with 2 decimal places (123456.78). This is what I came up with
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;
}
and its implementation in formly form
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);
}
}
}
]
}
];
What do I have to add to cover above scenario?
Upvotes: 0
Views: 4352
Reputation: 3458
Try regex below.
var regex = /^\d{1,6}(\.\d{1,2})?$/;
console.log(regex.test("123456"));
console.log(regex.test("123456.78"));
console.log(regex.test("123456.00"));
console.log(regex.test("12345.00"));
console.log(regex.test("12345.0"));
console.log(regex.test("12345.6"));
console.log(regex.test("12.34"));
console.log(regex.test("123456.789"));
Upvotes: 1
Reputation: 3653
If you don't want to add additional regex complexity, what you can do is make an additional check of maxLength before finally giving it a pass
var str = value.toFixed(2);
var maxLength = (str.indexOf(".") > -1 ? 8 : 6);
if (str.length > maxLength) {
return; //invalid input
}
Upvotes: 0
Reputation: 784
Trying this out on regex101 seems to fit you criteria.
Solution: ^(\d{6})?(\d{8}\.\d{2})?$
Group 1 ^(\d{6})?
- either 6 digits
Group 2 ^(\d{6})?(\d{8}\.\d{2})?$
- or 8 digits with 2 decimal place
Upvotes: 0