验证Laravel 5中的阿拉伯数字 [英] Validate Arabic Numbers in Laravel 5

查看:54
本文介绍了验证Laravel 5中的阿拉伯数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,其中包含一个供用户输入某些付款金额值的字段.此字段是类型编号的输入.

I have a form that contains a field for user to enter amount value of certain payment. This field is input of type number.

Laravel中针对此输入的验证规则为:

The validation rule in Laravel for this input is:

'amount' => 'required|numeric'

当我输入英文金额为: 1500 => 验证通过且一切正常.

When I enter the amount in English as: 1500 => The validation passes and everything is OK.

但是当我用阿拉伯语输入金额时: ١٥٠٠ => 验证失败,并显示以下错误消息:

But when I enter the amount in Arabic as: ١٥٠٠ => The validation fails with the following error message:

"validation.numeric"

"validation.numeric"

我应该手动验证此字段,还是对此问题有另一种解决方案?

Should I validate this field manually or is there another solution to this problem?

推荐答案

也许您可以创建自己的验证类型.

Maybe you can create your own validation type.

您可以在 app/Providers/AppServiceProvider.php 中将类似这样的内容添加到引导方法中.

You can add something like this to your boot method in app/Providers/AppServiceProvider.php.

Validator::extend('arabic_numbers', function ($attributes, $value, $parameters, $validation) {
  $arabic_numbers = [
    '٥',
    '١',
    // add more
  ];

  $input = $value;
  if (!$input) {
    return false;
  }
  $chars = preg_split('//u', $input, -1, PREG_SPLIT_NO_EMPTY);
  foreach ($chars as $char) {
    if (!in_array($char, $arabic_numbers)) {
      return false;
    }
  }

  return true;
});

您可以添加到现有规则,例如必填|阿拉伯数字.

You can add to your existing rule, e.g. required|arabic_numbers.

或使用类似这样的内容:

Or use something like this:

$input = '١';
$validator = Validator::make([
    'user_input' => $input,
], [
    'user_input' => 'required|arabic_numbers'
];

if ($validator->fails()) {
    //
}

您还可以通过多种其他方式使用,例如在自定义请求中:

Also you can use in many other ways for example in a custom request:

public function rules()
{
    return [
        'something' => 'required|arabic_numbers',
    ];
}

希望这会有所帮助.

这篇关于验证Laravel 5中的阿拉伯数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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