Tema: Re: SilverStripe custom fieldai
Autorius: Artūras Šlajus
Data: 2009-11-30 00:18:14
Artūras Šlajus wrote:
> Sveiki,
> 
> Gal kas dirba su SS ir pavyko priversti admino panelėje validuotis 
> custom fieldą su JS?
> 
> Nes pas mane tai visiškai ignoruoja. Serverio validacija veikia.
Kodas:

<?php

/**
  * Textarea that only allows emails separated by commas.
  *
  * @author Artūras 'arturaz' Šlajus <x11@arturaz.net>
  */
class EmailAreaField extends TextareaField {
   const ERROR_MESSAGE = "One of the emails in the field is invalid.";
   const EMAIL_REGEXP = '/^.+@.+\.[a-z]+$/i';

   public function validate() {
     foreach (split(",", $this->value) as $email) {
       $email = trim($email);

       if (! preg_match(self::EMAIL_REGEXP, $email)) {
         $validator->validationError(
           $this->name,
           self::ERROR_MESSAGE,
           "validation"
         );

         return false;
       }
     }

     return true;
   }

   public function jsValidation() {
     $formID = $this->form->FormName();
		$error = self::ERROR_MESSAGE;
     $regexp = self::EMAIL_REGEXP;
		$jsFunc =<<<JS
Behaviour.register({
	"#$formID": {
		validateEmailAreaField: function(fieldName) {
			var el = _CURRENT_FORM.elements[fieldName];
			if(!el || !el.value) return true;

       var parts = el.value.split(',');
       for (var index = 0; index < parts.length; index++) {
         var part = parts[index].strip();
         if (! el.value.match($regexp)) {
           validationError(el, "$error", "validation");
           return false;
         }
       }

       return true;
		}
	}
});
JS;
		//fix for the problem with more than one form on a page.
		Requirements::customScript($jsFunc, 'func_validateEmailAreaField' . '_' . 
$formID);

		return <<<JS
if(typeof fromAnOnBlur != 'undefined'){
	if(fromAnOnBlur.name == '$this->name')
		$('$formID').validateEmailAreaField('$this->name');
}else{
	$('$formID').validateEmailAreaField('$this->name');
}
JS;
   }
}
?>