[Symfony1.4] How to Set Validation Errors on Individual Fields with PostValidator

Tadashi Shigeoka ·  Tue, November 15, 2011

In Symfony1.4, I researched how to set validation errors on individual fields with PostValidator, so here’s a memo.

・Reference: postValidatorから個別のフィールドにエラーを設定 - ゆっくり*ゆっくり

Initially, I was simply using sfValidatorError to display validation error messages, but this approach results in a GlobalError.

// Validator for checking duplicate login IDs
class ValidatorSameLoginId extends sfValidatorBase{
  protected function doClean($value){
    // Get record with the same login ID from DB
    $user = UserTable::getInstance()->getOneByLoginId($value['login_id']);
    // If a record with the same login ID already exists, validation error
    if($user != false){
      throw new sfValidatorError($this, '同じログインIDが既に登録されています', array('value' => $value));
    }
    return $value;
  }
}

To make this a NamedError for a single field instead,

if($user != false){
  throw new sfValidatorError($this, '同じログインIDが既に登録されています', array('value' => $value));
}

you can rewrite this part using sfValidatorErrorSchema as follows to display validation errors on individual fields:

symfony API » sfValidatorErrorSchema Class | symfony | Web PHP Framework

class ValidatorSameLoginId extends sfValidatorBase{
  protected function doClean($value){
    // Get record with the same login ID from DB
    $user = UserTable::getInstance()->getOneByLoginId($value['login_id']);
    // If a record with the same login ID already exists, validation error
    if($user != false){
      throw new sfValidatorErrorSchema($this, array(
        'login_id' => new sfValidatorError($this, 'The same login ID is already registered' /* 同じログインIDが既に登録されています */),
      ));
    }
    return $value;
  }
}

That’s all from the Gemba.