本文介绍了仅允许6位数字或8位数字,小数点后2位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个验证器,用于检查数字是否为数字,并确保小数位后允许有2位数字。这不包括的数字是6位数字,没有小数位(123456)或8位数,2位小数(123456.78)。这就是我想出的结果
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(格式){
if(value< min || value> max){
format = false;
}
}
返回格式;
}
及其实现形式
vm.fields = [
{
className:'row',
fieldGroup:[
{
className:'col-xs-6',
key:'payment',
type:'input',
templateOptions:{
label:'Payment',
required:false,
maxlength:8
},
验证器:{
cost:function(viewValue,modelValue,scope){
var value = modelValue || viewValue;
返回validateInt2Dec(value);
}
}
}
]
}
];
我需要添加什么才能涵盖上述情况?
解决方案
试试下面的正则表达式。
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));控制台.LOG(regex.test( 12.34));执行console.log(regex.test( 123456.789));
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?
解决方案
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"));
这篇关于仅允许6位数字或8位数字,小数点后2位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!