概述 快速入门 教程 手册 最佳实践 组件 参考 贡献

发布于 2015-08-27 16:43:38 | 149 次阅读 | 评论: 0 | 来源: 网络整理

This constraint allows you to use an expression for more complex, dynamic validation. See Basic Usage for an example. See Callback for a different constraint that gives you similar flexibility.

Applies to class or property/method
Options
Class Expression
Validator ExpressionValidator

Basic Usage

Imagine you have a class BlogPost with category and isTechnicalPost properties:

namespace AcmeDemoBundleModel;

use SymfonyComponentValidatorConstraints as Assert;

class BlogPost
{
    private $category;

    private $isTechnicalPost;

    // ...

    public function getCategory()
    {
        return $this->category;
    }

    public function setIsTechnicalPost($isTechnicalPost)
    {
        $this->isTechnicalPost = $isTechnicalPost;
    }

    // ...
}

To validate the object, you have some special requirements:

  1. If isTechnicalPost is true, then category must be either php or symfony;
  2. If isTechnicalPost is false, then category can be anything.

One way to accomplish this is with the Expression constraint:

  • YAML
    # src/Acme/DemoBundle/Resources/config/validation.yml
    AcmeDemoBundleModelBlogPost:
        constraints:
            - Expression:
                expression: "this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()"
                message: "If this is a tech post, the category should be either php or symfony!"
    
  • Annotations
    // src/Acme/DemoBundle/Model/BlogPost.php
    namespace AcmeDemoBundleModel;
    
    use SymfonyComponentValidatorConstraints as Assert;
    
    /**
     * @AssertExpression(
     *     "this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()",
     *     message="If this is a tech post, the category should be either php or symfony!"
     * )
     */
    class BlogPost
    {
        // ...
    }
    
  • XML
    <!-- src/Acme/DemoBundle/Resources/config/validation.xml -->
    <?xml version="1.0" encoding="UTF-8" ?>
    <constraint-mapping xmlns="http://symfony.com/schema/dic/constraint-mapping"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://symfony.com/schema/dic/constraint-mapping http://symfony.com/schema/dic/constraint-mapping/constraint-mapping-1.0.xsd">
        <class name="AcmeDemoBundleModelBlogPost">
            <constraint name="Expression">
                <option name="expression">
                    this.getCategory() in ['php', 'symfony'] or !this.isTechnicalPost()
                </option>
                <option name="message">
                    If this is a tech post, the category should be either php or symfony!
                </option>
            </constraint>
        </class>
    </constraint-mapping>
    
  • PHP
    // src/Acme/DemoBundle/Model/BlogPost.php
    namespace AcmeDemoBundleModel;
    
    use SymfonyComponentValidatorMappingClassMetadata;
    use SymfonyComponentValidatorConstraints as Assert;
    
    class BlogPost
    {
        public static function loadValidatorMetadata(ClassMetadata $metadata)
        {
            $metadata->addConstraint(new AssertExpression(array(
                'expression' => 'this.getCategory() in ["php", "symfony"] or !this.isTechnicalPost()',
                'message' => 'If this is a tech post, the category should be either php or symfony!',
            )));
        }
    
        // ...
    }
    

The expression option is the expression that must return true in order for validation to pass. To learn more about the expression language syntax, see The Expression Syntax.

For more information about the expression and what variables are available to you, see the expression option details below.

Available Options

expression

type: string [default option]

The expression that will be evaluated. If the expression evaluates to a false value (using ==, not ===), validation will fail.

To learn more about the expression language syntax, see The Expression Syntax.

Inside of the expression, you have access to up to 2 variables:

Depending on how you use the constraint, you have access to 1 or 2 variables in your expression:

  • this: The object being validated (e.g. an instance of BlogPost);
  • value: The value of the property being validated (only available when the constraint is applied directly to a property);

message

type: string default: This value is not valid.

The default message supplied when the expression evaluates to false.

payload

type: mixed default: null

2.6 新版功能: The payload option was introduced in Symfony 2.6.

This option can be used to attach arbitrary domain-specific data to a constraint. The configured payload is not used by the Validator component, but its processing is completely up to.

For example, you may want to used several error levels to present failed constraint differently in the front-end depending on the severity of the error.

最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务