Symfony2 comes already with a range of predefined validators you can use to validate your forms but at one point or another it might be possible that you want to create your own field validator.

There is already a good how-to page in the Symfony2 Cookbook. But if you want to create a validator without any external dependencies the cookbook documentation might seem a little bit misleading since it does not explain in detail how to that.

You do not need to register your validation constraint as a service if it has no external dependencies.

In order to explain the creation of a custom validation constraint I will create a simple zip code validation constraint. To keep it simple I will just use a regex to check if the zip code is valid. Symfony2 provides already a regex validation constraint but I will start "from scratch" to explain the process in detail.

Simple Zip Code Validator

Each validation constraint consists of a "constraint" class and a "constraint validator" class. The Constraint base class (Symfony\Component\Validator\Constraint) has a validatedBy() method which is responsible to reference its validator class. You can override it to suit it for your needs. We will use the default implementation in this example.

<?php
// Symfony\Component\Validator\Constraint

public function validatedBy()
{
   return get_class($this).'Validator';
}

We will start to implement our constraint class. In this case it is pretty simple. Even the message field is optional.

<?php
/*
 *  The namespace does not matter, but if you are using the default validateBy() implementation,
 *  the constraint and the constraint validator classes have to be in the same namespace
 */
namespace SomeNamespace\SomeBundle\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class ZipCode extends Constraint
{
    // message is optional, you can also pass the message in the annotation
    public $message = 'The zip code should consist of 5 digits. Your input was {{ value }}.';
}

In the next step we will implement the constraint validator class. In order to use our own validation logic we have to override the isValid() function.

<?php
namespace SomeNamespace\SomeBundle\Component\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

class ZipCodeValidator extends ConstraintValidator
{
    /*
     * Very simple validation logic to test german zip codes,
     * usually german zip codes consists of 5 digits
     */
    private function isValidZipCode($value){
        return 0 === preg_match('/\d{5}/', $value);
    }

    public function isValid($value, Constraint $constraint)
    {
        if( $this->isValidZipCode($value) === false ) {
            $this->setMessage($constraint->message, array('{{ value }}' => $value));

            return false;
        }

        return true;
    }
}

In the last step we have to add the constraint to our entity field which we want to validate.

<?php
namespace SomeNamespace\SomeBundle\Model;

// the default symfony constraints
use Symfony\Component\Validator\Constraints as Assert;
// our custom made constraints
use SomeNamespace\SomeBundle\Component\Validator\Constraints as CustomAssert;

class Customer
{
    /**
     * @Assert\NotBlank()
     * @Assert\MinLength(limit=2)
     * @Assert\MaxLength(limit=20)
     */
    private $name;

    /**
     * @CustomAssert\ZipCode()
     */
    private $zipCode;

    /**
     * @CustomAssert\ZipCode(message="You can pass your own message here, like on the default constraints")
     */
    private $alternateZipCode;

    /* ... */

}

Now we are done and we can use our constraint to validate the zip code of our Customer entity.

If you want to create a custom validator in relation to another field (e.g. a "retype your email" field) I recommend you this article by Steven Brown.


In MySQL it is pretty easy to get the date part of a datetime since MySQL provides native functions to do this:

DATE(…) AND CURDATE( )

SELECT DATE('2011-09-10 11:24:03');
#Prints 2011-09-10

SELECT CURDATE()
#Prints the current date, e.g. 2011-09-10

Unfortunately T-SQL does not ...

read more

If you want to call a JavaScript function repeatedly with a fixed time delay, you would probably use setInterval().

A simple example might look like this

var functionToRepeat = function () {
  console.log('Executed: ' + new Date());
}
window.setInterval(functionToRepeat, 1000);

The example above will call functionToRepeat every second and prints the current ...

read more

Since the introduction of SQL Server 2005, Microsoft added support of XQuery to its feature set. XQuery is a query language which provides the means to read and write XML data.

In the following example I use XQuery to parse a XML string and select a set of attributes. Let ...

read more

Recursion in T-SQL

Posted on 25 May, 2011 by Janosch Woschitz

Today I learned that you can perform recursion also in a T-SQL procedure (and I’m not talking about CLR Stored Procedures, just plain SQL).

A colleague asked me if it is possible to perform recursive algorithms in SQL. I never thought about recursion in SQL before (I will leave ...

read more