在CakePHP中验证和转换十进制值 [英] Validating and transforming decimal values in CakePHP

查看:185
本文介绍了在CakePHP中验证和转换十进制值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用CakePHP开发一个处理货币价值的应用程序。客户端希望数字具有自定义格式,例如 1.275,34 ,即在整数部分中使用点作为分隔符,并使用逗号作为小数部分的分隔符。 / p>

我想知道什么是最好的方法来管理这个,因为我需要做两个基本的事情:


  1. 根据自定义格式验证以表单形式写入的值。

  2. 根据MySQL的列数据类型预期的格式转换这些值( decimal (18,2)在这种情况下, 1275.34 在上面的示例)。

我想我有这些选项,但我不完全满意任何,因为几个模型工作与自定义格式,这意味着复制一些代码:




  • 在调用 $ this-> Model-> save()之前,验证并转换控制器中的值,

  • 使用模型中的自定义规则( var $ validate 数组)验证数据并对其进行转换, / li>


您推荐什么?是否有其他方法处理这个问题?



谢谢!

解决方案

1.234,56格式是欧洲的货币格式,所以你可能最好让整个应用程序使用这种格式。您需要做的是使用 setlocale(LC_MONETARY,$ locale)设置应用程序的货币区域设置。例如:

  setlocale(LC_MONETARY,'it_IT'); 

然后,使用 money_format 格式化您的货币字符串,并使用 :beforeValidate()回调以在验证之前按任何货币输入,因此您可以根据标准十进制格式进行验证。 此相关问题可能有用


I'm developing an application with CakePHP that handles monetary values. The client wants the numbers to have a custom format like 1.275,34, i.e. a dot as the delimiter in the integer part and a comma as the delimiter of the decimal part.

I'm wondering what's the best approach to manage this, since i need to do two basic things:

  1. Validate values written in forms according to that custom format.
  2. Transform those values according to the format expected by MySQL's column data type (decimal(18,2) in this case, 1275.34 in the example above).

I think I have these options but I'm not completely happy with any because several models work with that custom format and that means replicating some code:

  • Validate and transform the value in the controller before calling $this->Model->save(), maybe using a Component.
  • Validate the data using custom rules in model (var $validate array) and transforming them, maybe using a Behavior.

What do you recommend? Is there any other approach to handle this?

Thanks!

解决方案

The "1.234,56" format is the European money format, so you're probably better off making the entire app use this format. What you need to do is set the monetary locale of your app, using setlocale(LC_MONETARY,$locale). So, for example:

setlocale(LC_MONETARY, 'it_IT');

Then, you use money_format to format your currency strings appropriately, and use a Model::beforeValidate() callback to massage any currency input before validation, so you can validate against standard decimal format. This related question may be useful.

这篇关于在CakePHP中验证和转换十进制值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆