Validasi username di symfony menggunakan validator

Awalnya sih g kepikiran juga, kalo username kudu di validasi (parah..parah.. ), tapi setelah ngeliat banyak orang yang ngisi ‘username’ sama dengan isian ‘nama’ di salah satu aplikasi yg kubikin, akhirnya nyoba2 googling.. dan alhamdulillah nemu juga disini.
Bagaimana mengimplementasikan validasi tersebut kalo pake validator-nya symfony?.. mmhhh.. g susah kok, dan saya juga yakin, temen2 pasti bisa.

<?php
//source: http://network-13.com/thread/c37f51d20b6b7d57
class sfValidatorUsername extends sfValidatorString
{
 protected function configure($options = array(), $messages = array())
 {
   parent::configure($options, $messages);
   $this-&gt;addMessage('first_char', "username can't begin with number or underscores");
   $this-&gt;addMessage('last_char', "username can't end with underscores");
   $this-&gt;addMessage('double_underscores', "username can't have consecutive underscores");
   $this-&gt;setMessage('invalid', "username can only have letters a-z, numbers 0-9 and an underscore");
 }

 protected function doClean($value)
 {
   $clean = parent::doClean($value);
   $string = strtolower($clean);
   if(!preg_match("/^(?i)[a-z0-9_]*$/", $string))
   {
     throw new sfValidatorError($this, 'invalid', array('value'=&gt;$value));
   }
   elseif(!preg_match("/^(?![0-9_]).*$/", $string))
   {
     throw new sfValidatorError($this, 'first_char', array('value'=&gt;$value));
   }
   elseif(preg_match("/__/", $string))
   {
     throw new sfValidatorError($this, 'double_underscores', array('value'=&gt;$value));
   }
   elseif(substr($string(strlen($string) - 1), strlen($string)) == "_")
   {
     throw new sfValidatorError($this, 'last_char', array('value'=&gt;$value));
   }
   return $clean;
  }
}

dan itu versi saya.. kalo ada ide yg laen.. silahkan di share di comment.. ty

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: