跳到内容

Url

编辑此页

验证值是否为有效的 URL 字符串。

适用于 属性或方法
Url
验证器 UrlValidator

基本用法

1
2
3
4
5
6
7
8
9
10
// src/Entity/Author.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    #[Assert\Url]
    protected string $bioUrl;
}

此约束不检查给定 URL 的主机是否真实存在,因为 DNS 记录的信息不可靠。如果您仍然想检查,请使用 checkdnsrr PHP 函数。

注意

与大多数其他约束一样,null 和空字符串被认为是有效值。这是为了允许它们成为可选值。如果该值是强制性的,一个常见的解决方案是将此约束与 NotBlank 结合使用。

选项

groups

类型: array | string 默认值: null

它定义了此约束的验证组。阅读更多关于 验证组 的信息。

message

类型: string 默认值: 该值不是有效的 URL。

如果 URL 无效,则显示此消息。

您可以在此消息中使用以下参数

参数 描述
{{ value }} 当前(无效)值
{{ label }} 对应的表单字段标签
1
2
3
4
5
6
7
8
9
10
11
12
// src/Entity/Author.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    #[Assert\Url(
        message: 'The url {{ value }} is not a valid url',
    )]
    protected string $bioUrl;
}

normalizer

类型: 一个 PHP 可调用对象 默认值: null

此选项允许定义在检查给定值是否有效之前应用于该值的 PHP 可调用对象。

例如,您可能希望传递 'trim' 字符串以应用 trim PHP 函数,以便在验证期间忽略前导和尾随空格。

payload

类型: mixed 默认值: null

此选项可用于将任意特定于域的数据附加到约束。配置的 payload 不会被 Validator 组件使用,但其处理完全取决于您。

例如,您可能希望使用 多个错误级别,以便根据错误严重程度在前端以不同方式呈现失败的约束。

protocols

类型: array 默认值: ['http', 'https']

被认为是 URL 有效的协议。例如,如果您也认为 ftp:// 类型的 URL 有效,请重新定义 protocols 数组,列出 httphttpsftp

1
2
3
4
5
6
7
8
9
10
11
12
// src/Entity/Author.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    #[Assert\Url(
        protocols: ['http', 'https', 'ftp'],
    )]
    protected string $bioUrl;
}

relativeProtocol

类型: boolean 默认值: false

如果为 true,则在验证给定 URL 的语法时,协议被认为是可选的。这意味着 http://https:// 都是有效的,但包含无协议的相对 URL(例如 //example.com)也是有效的。

1
2
3
4
5
6
7
8
9
10
11
12
// src/Entity/Author.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Author
{
    #[Assert\Url(
        relativeProtocol: true,
    )]
    protected string $bioUrl;
}

requireTld

类型: boolean 默认值: false

7.1

requireTld 选项在 Symfony 7.1 中引入。

7.1

自 Symfony 7.1 起,不设置 requireTld 选项已被弃用,在 Symfony 8.0 中将默认为 true

默认情况下,像 https://aaahttps://foobar 这样的 URL 被认为是有效的,因为根据 URL 规范,它们在技术上是正确的。如果您将此选项设置为 true,则 URL 的主机部分必须包含 TLD(顶级域名):例如,https://example.com 将是有效的,但 https://example 将无效。

注意

此约束不验证给定的 TLD 值是否包含在 官方顶级域名列表 中(因为该列表在不断增长,并且很难跟踪它)。

tldMessage

类型: string 默认值: 此 URL 不包含 TLD。

7.1

tldMessage 选项在 Symfony 7.1 中引入。

如果 requireTld 选项设置为 true 且 URL 不包含至少一个 TLD,则显示此消息。

您可以在此消息中使用以下参数

参数 描述
{{ value }} 当前(无效)值
{{ label }} 对应的表单字段标签
1
2
3
4
5
6
7
8
9
10
11
12
13
// src/Entity/Website.php
namespace App\Entity;

use Symfony\Component\Validator\Constraints as Assert;

class Website
{
    #[Assert\Url(
        requireTld: true,
        tldMessage: 'Add at least one TLD to the {{ value }} URL.',
    )]
    protected string $homepageUrl;
}
本作品,包括代码示例,根据 Creative Commons BY-SA 3.0 许可协议获得许可。
目录
    版本