Skip to content

WordCount

Edit this page

7.2

The WordCount constraint was introduced in Symfony 7.2.

Validates that a string (or an object implementing the Stringable PHP interface) contains a given number of words. Internally, this constraint uses the IntlBreakIterator class to count the words depending on your locale.

Applies to property or method
Class WordCount
Validator WordCountValidator

Basic Usage

If you wanted to ensure that the content property of a BlogPostDTO class contains between 100 and 200 words, you could do the following:

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

use Symfony\Component\Validator\Constraints as Assert;

class BlogPostDTO
{
    #[Assert\WordCount(min: 100, max: 200)]
    protected string $content;
}

Options

min

type: integer default: null

The minimum number of words that the value must contain.

max

type: integer default: null

The maximum number of words that the value must contain.

locale

type: string default: null

The locale to use for counting the words by using the IntlBreakIterator class. The default value (null) means that the constraint uses the current user locale.

groups

type: array | string default: null

It defines the validation group or groups of this constraint. Read more about validation groups.

minMessage

type: string default: This value is too short. It should contain at least one word.|This value is too short. It should contain at least {{ min }} words.

This is the message that will be shown if the value does not contain at least the minimum number of words.

You can use the following parameters in this message:

Parameter Description
{{ min }} The minimum number of words
{{ count }} The actual number of words

maxMessage

type: string default: This value is too long. It should contain one word.|This value is too long. It should contain {{ max }} words or less.

This is the message that will be shown if the value contains more than the maximum number of words.

You can use the following parameters in this message:

Parameter Description
{{ max }} The maximum number of words
{{ count }} The actual number of words

payload

type: mixed default: null

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 you.

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

This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version