yii2 number max, min with dot and comma 验证
yii2 number max, min with dot and comma validation
在我的脚本中,我需要使用逗号和点以及最大值和最小值来验证价格。
这是我的规则()
return [
[['price'], 'required', 'message' => 'Price ...'],
[['price'], 'number', 'numberPattern' => '/^[0-9]{1,2}([\.,][0-9]{1,2})*$/',
'message' => 'Price ...', 'max' => 25, min => '0'],
];
当我输入 25.00 (.dot) 这样的价格时效果很好,但是当我输入 25,01 (, 逗号) 时验证不起作用。你知道如何让它发挥作用吗?
我发现此解决方案适用于所有输入,您无需寻找特定的小部件选项。在你的 View 文件中(最好在底部)注册 JS:
$this->registerJs("
$(document).ready(function() {
$(document).on('keyup', 'input', function(e){
$(this).val($(this).val().replace(/[,]/g, '.'));
});
});
");
这会将所有输入中的所有 逗号 更改为 点。我自己测试过(当然),效果很好。
但是,如果您希望以仅在某些输入中应用的方式进行更改,则必须将自定义 class 添加到他们每个人然后将此代码稍微更改为:
$this->registerJs("
$(document).ready(function() {
$(document).on('keyup', '.CustomClassName', function(e){
$(this).val($(this).val().replace(/[,]/g, '.'));
});
});
");
我认为这比使用小部件的选项要好,因为您将需要找到这样的选项(您甚至不知道这个选项一开始是否存在),而只要您使用这个选项,它就会一直存在不要忘记添加自定义 class 并注册此 JavaScript 代码。
在我的脚本中,我需要使用逗号和点以及最大值和最小值来验证价格。 这是我的规则()
return [
[['price'], 'required', 'message' => 'Price ...'],
[['price'], 'number', 'numberPattern' => '/^[0-9]{1,2}([\.,][0-9]{1,2})*$/',
'message' => 'Price ...', 'max' => 25, min => '0'],
];
当我输入 25.00 (.dot) 这样的价格时效果很好,但是当我输入 25,01 (, 逗号) 时验证不起作用。你知道如何让它发挥作用吗?
我发现此解决方案适用于所有输入,您无需寻找特定的小部件选项。在你的 View 文件中(最好在底部)注册 JS:
$this->registerJs("
$(document).ready(function() {
$(document).on('keyup', 'input', function(e){
$(this).val($(this).val().replace(/[,]/g, '.'));
});
});
");
这会将所有输入中的所有 逗号 更改为 点。我自己测试过(当然),效果很好。
但是,如果您希望以仅在某些输入中应用的方式进行更改,则必须将自定义 class 添加到他们每个人然后将此代码稍微更改为:
$this->registerJs("
$(document).ready(function() {
$(document).on('keyup', '.CustomClassName', function(e){
$(this).val($(this).val().replace(/[,]/g, '.'));
});
});
");
我认为这比使用小部件的选项要好,因为您将需要找到这样的选项(您甚至不知道这个选项一开始是否存在),而只要您使用这个选项,它就会一直存在不要忘记添加自定义 class 并注册此 JavaScript 代码。