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

发布于 2015-08-27 16:50:15 | 253 次阅读 | 评论: 0 | 来源: 网络整理

Validates that a value is a valid “file”, which can be one of the following:

  • A string (or object with a __toString() method) path to an existing file;
  • A valid File object (including objects of class UploadedFile).

This constraint is commonly used in forms with the file form type.

小技巧

If the file you’re validating is an image, try the Image constraint.

Applies to property or method
Options
Class File
Validator FileValidator

Basic Usage

This constraint is most commonly used on a property that will be rendered in a form as a file form type. For example, suppose you’re creating an author form where you can upload a “bio” PDF for the author. In your form, the bioFile property would be a file type. The Author class might look as follows:

// src/Acme/BlogBundle/Entity/Author.php
namespace AcmeBlogBundleEntity;

use SymfonyComponentHttpFoundationFileFile;

class Author
{
    protected $bioFile;

    public function setBioFile(File $file = null)
    {
        $this->bioFile = $file;
    }

    public function getBioFile()
    {
        return $this->bioFile;
    }
}

To guarantee that the bioFile File object is valid, and that it is below a certain file size and a valid PDF, add the following:

  • YAML
    # src/Acme/BlogBundle/Resources/config/validation.yml
    AcmeBlogBundleEntityAuthor:
        properties:
            bioFile:
                - File:
                    maxSize: 1024k
                    mimeTypes: [application/pdf, application/x-pdf]
                    mimeTypesMessage: Please upload a valid PDF
    
  • Annotations
    // src/Acme/BlogBundle/Entity/Author.php
    namespace AcmeBlogBundleEntity;
    
    use SymfonyComponentValidatorConstraints as Assert;
    
    class Author
    {
        /**
         * @AssertFile(
         *     maxSize = "1024k",
         *     mimeTypes = {"application/pdf", "application/x-pdf"},
         *     mimeTypesMessage = "Please upload a valid PDF"
         * )
         */
        protected $bioFile;
    }
    
  • XML
    <!-- src/Acme/BlogBundle/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="AcmeBlogBundleEntityAuthor">
            <property name="bioFile">
                <constraint name="File">
                    <option name="maxSize">1024k</option>
                    <option name="mimeTypes">
                        <value>application/pdf</value>
                        <value>application/x-pdf</value>
                    </option>
                    <option name="mimeTypesMessage">Please upload a valid PDF</option>
                </constraint>
            </property>
        </class>
    </constraint-mapping>
    
  • PHP
    // src/Acme/BlogBundle/Entity/Author.php
    namespace AcmeBlogBundleEntity;
    
    use SymfonyComponentValidatorMappingClassMetadata;
    use SymfonyComponentValidatorConstraints as Assert;
    
    class Author
    {
        public static function loadValidatorMetadata(ClassMetadata $metadata)
        {
            $metadata->addPropertyConstraint('bioFile', new AssertFile(array(
                'maxSize' => '1024k',
                'mimeTypes' => array(
                    'application/pdf',
                    'application/x-pdf',
                ),
                'mimeTypesMessage' => 'Please upload a valid PDF',
            )));
        }
    }
    

The bioFile property is validated to guarantee that it is a real file. Its size and mime type are also validated because the appropriate options have been specified.

Options

maxSize

2.6 新版功能: The suffixes Ki and Mi were introduced in Symfony 2.6.

type: mixed

If set, the size of the underlying file must be below this file size in order to be valid. The size of the file can be given in one of the following formats:

Suffix Unit Name value e.g.
  byte 1 byte 4096
k kilobyte 1,000 bytes 200k
M megabyte 1,000,000 bytes 2M
Ki kibibyte 1,024 bytes 32Ki
Mi mebibyte 1,048,576 bytes 8Mi

For more information about the difference between binary and SI prefixes, see Wikipedia: Binary prefix.

binaryFormat

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

type: boolean default: null

When true, the sizes will be displayed in messages with binary-prefixed units (KiB, MiB). When false, the sizes will be displayed with SI-prefixed units (kB, MB). When null, then the binaryFormat will be guessed from the value defined in the maxSize option.

For more information about the difference between binary and SI prefixes, see Wikipedia: Binary prefix.

mimeTypes

type: array or string

If set, the validator will check that the mime type of the underlying file is equal to the given mime type (if a string) or exists in the collection of given mime types (if an array).

You can find a list of existing mime types on the IANA website.

maxSizeMessage

type: string default: The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.

The message displayed if the file is larger than the maxSize option.

mimeTypesMessage

type: string default: The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.

The message displayed if the mime type of the file is not a valid mime type per the mimeTypes option.

disallowEmptyMessage

2.6 新版功能: The disallowEmptyMessage option was introduced in Symfony 2.6. Prior to 2.6, if the user uploaded an empty file, no validation error occurred.

type: string default: An empty file is not allowed.

This constraint checks if the uploaded file is empty (i.e. 0 bytes). If it is, this message is displayed.

notFoundMessage

type: string default: The file could not be found.

The message displayed if no file can be found at the given path. This error is only likely if the underlying value is a string path, as a File object cannot be constructed with an invalid file path.

notReadableMessage

type: string default: The file is not readable.

The message displayed if the file exists, but the PHP is_readable function fails when passed the path to the file.

uploadIniSizeErrorMessage

type: string default: The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.

The message that is displayed if the uploaded file is larger than the upload_max_filesize php.ini setting.

uploadFormSizeErrorMessage

type: string default: The file is too large.

The message that is displayed if the uploaded file is larger than allowed by the HTML file input field.

uploadErrorMessage

type: string default: The file could not be uploaded.

The message that is displayed if the uploaded file could not be uploaded for some unknown reason, such as the file upload failed or it couldn’t be written to disk.

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号  版权声明  广告服务