【问题标题】:Custom attribute name in Ardent validation messageArdent 验证消息中的自定义属性名称
【发布时间】:2014-11-16 05:31:10
【问题描述】:

我在我的 Laravel 项目中使用 Ardent,因为我喜欢它很棒的模型验证功能。现在我需要在验证错误消息中设置人类可以理解的属性值。 我读到可以通过在validation.php文件(lang文件夹)中设置$attributes数组来完成。

由于我来自 Yii,我想知道是否有办法在模型基础上指定属性名称,而不是在validation.php 语言文件中全局指定。

例如,如果我有两个模型,Employee 和 Company,都具有“name”属性,我想将“name”属性的显示值分别设置为“Employee name”和“Company name”。

【问题讨论】:

    标签: laravel laravel-4 ardent laravel-validation


    【解决方案1】:

    试试这个。它来自 GitHub 上的文档。我从未与 Ardent 合作过,但它实际上有相当不错的文章。

    class Employee extends \LaravelBook\Ardent\Ardent {
        public static $rules = array(
            'name' => 'Required|Alpha_Dash'
        );
        public static $customMessages = array(
            'required' => 'The Employee :attribute field is required.',
            'alpha_dash' => 'The Employee :attribute field must be Letters and Dashes only.'
        );
    }
    

    由于这些自定义消息是在员工类中定义的,因此它们仅适用于此类的输入。您可以对 Company 类执行相同操作:

    class Company extends \LaravelBook\Ardent\Ardent {
        public static $rules = array(
            'name' => 'Required|Alpha_Dash'
        );
        public static $customMessages = array(
            'required' => 'The Company :attribute field is required.',
            'alpha_dash' => 'The Company :attribute field must be Letters and Dashes only.'
        );
    }
    

    我认为这应该可行。但是,我没有任何方法可以测试它。另一种选择是使用自定义规则,例如

    'name' => 'Employee_Required|Employee_Aplha_Dash'
    

    并在 Laravel 的验证中定义这些。但无论如何,我希望这会有所帮助!

    【讨论】:

    • 这只是一种解决方法。也许 Ardent 不支持这个功能。
    • 我已经设法更多地研究了 Ardent,除了上面的方法,我看不到实现您想要的功能的方法(即不修改 Ardent 的原始源代码)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-24
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    相关资源
    最近更新 更多