如何在验证中验证值的总和是否相等

时间:2018-04-23 06:26:25

标签: laravel laravel-5 vuejs2

我有这个会计项目,我需要在保存到数据库之前验证借方和贷方是否相等。

例如

accounts: [
    {

        id: 1,
        account_id: 1,
        debit:  1000
    },
    {
        id: 2,
        account_id: 5,
        credit: 1500
    },
    {
        id: 3,
        account_id: 8,
        debit: 500
    }
]

顺便说一下,我正在使用axios和lodash。

axios.post('/api/journals', {

    accounts : map(this.accounts, function(account) {

        account_id: account.account_id,
        debit: account.debit,
        credit: account.credit
    })
}

任何人都可以建议如何实施此验证规则。

1 个答案:

答案 0 :(得分:0)

验证规则与Laravel或VueJS无关。您只需要使用lodash迭代accounts数组,分别对借方和贷方编号求和,然后比较它们:

var debitSum = _.reduce(data.accounts, function(sum, account) {
  return (account.debit || 0) + sum;
}, 0);

var creditSum = _.reduce(data.accounts, function(sum, account) {
  return (account.credit || 0) + sum;
}, 0);

console.log('Debit: ' + debitSum + '; Credit: ' + creditSum);

if (debitSum !== creditSum) {
    // Debit and credit sums do not match
} else {
    // Debit and credit sums match
}

上面的代码使用_.reduce()方法计算借方/贷方金额的总和。由于debitcredit密钥无法保证始终存在,因此我们使用||运算符在其为假时指定值0(例如undefinednull0,空字符串等。)

这是一个概念验证示例:



var data = { accounts: [{
    id: 1,
    account_id: 1,
    debit: 1000
  },
  {
    id: 2,
    account_id: 5,
    credit: 1500
  },
  {
    id: 3,
    account_id: 8,
    debit: 500
  }
]};

var debitSum = _.reduce(data.accounts, function(sum, account) {
  return (account.debit || 0) + sum;
}, 0);

var creditSum = _.reduce(data.accounts, function(sum, account) {
  return (account.credit || 0) + sum;
}, 0);

console.log('Debit: ' + debitSum + '; Credit: ' + creditSum);

if (debitSum !== creditSum) {
  console.log('Debit and credit are not equal!');
} else {
  console.log('All ok');
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
&#13;
&#13;
&#13;