[gelöst] Validieren der Formulareingaben mittels Ajax

Hallo zusammen, ich beschäftige mich gerade mit der Ajax Validierung von Formulareingaben im Frontend. Dazu habe ich mich mir den Register Controller (\engine\Shopware\Controllers\Frontend\register.php) näher angesehen und darauf aufbauend meinen Controller aufgebaut. Jetzt möchte ich noch die Validierung einbauen. ajaxValidateEmailAction() in der Mail.php soll die Validierung übernehmen. Jetzt muss ich dem Mail Feld noch irgendwie sagen, dass es diese Funktion für die Validierung nutzen soll. Der tpl Code für die Mail lautet wie folgt <input name="mail[email]" type="text" id="mail_email" value="{$form_data.email|escape}" class="text required email {if $error_flags.email}instyle_error{/if}"> Ändere ich id="mail\_email" in id="register\_personal\_email" ab, dann wird beim Verlassen des Mailfelds laut Firebug ein Post auf localhost/register ausgeführt. Wie ändere ich meinen Code entsprechend ab, dass die Validierung von der richtigen Funktion übernommen wird. Freue mich um jede Antwort :slight_smile: Mein Plugin Controller: Controllers\Frontend\Mail.php [code]<?php class Shopware_Controllers_Frontend_Mail extends Enlight_Controller_Action
{

	protected $session;
protected $admin;
protected $system;
protected $post;
protected $error;

/**
 * Calls when the controller will be initialized
 *
 * @return void
 */
public function init()
{
	
            $this->session = Shopware()-\>Session(); $this-\>admin = Shopware()-\>Modules()-\>Admin(); $this-\>system = Shopware()-\>Modules()-\>System(); $this-\>post = $this-\>request-\>getParam('mail'); $this-\>View()-\>addTemplateDir(dirname(\_\_FILE\_\_) . "/../../Views/"); } /\*\* \* Will be called from the dispatcher before an action is processed \* \* @return void \*/ public function preDispatch() { $this-\>View()-\>setScope(Enlight\_Template\_Manager::SCOPE\_PARENT); if(!isset($this-\>View()-\>mail)) { $this-\>View()-\>mail = new ArrayObject(array(), ArrayObject::ARRAY\_AS\_PROPS); } if(!isset($this-\>session['sMail'])) { $this-\>session['sMail'] = new ArrayObject(array(), ArrayObject::ARRAY\_AS\_PROPS); } if(in\_array($this-\>Request()-\>getActionName(), array('ajax\_validate\_email'))) { Shopware()-\>Plugins()-\>Controller()-\>ViewRenderer()-\>setNoRender(); } } public function indexAction() { $this-\>View()-\>loadTemplate("frontend/index.tpl"); $this-\>mailAction(); } public function mailAction() { if(!isset($this-\>View()-\>mail)) { $this-\>View()-\>mail = new ArrayObject(array(), ArrayObject::ARRAY\_AS\_PROPS); } if(!isset($this-\>View()-\>mail-\>form\_data)) { $this-\>View()-\>mail-\>form\_data = new ArrayObject(array(), ArrayObject::ARRAY\_AS\_PROPS); } } /\*\* \* Checks if the given email is ok. \*/ public function ajaxValidateEmailAction() { $error\_flags = array(); $error\_messages = array(); if (empty($this-\>post['email'])) { } elseif (($validator = new Zend\_Validate\_EmailAddress()) && !$validator-\>isValid($this-\>post['email'])) { $error\_messages[] = Shopware()-\>Snippets()-\>getNamespace("frontend")-\>get('MailAjaxEmailNotValid', 'Please enter a valid mail address.', true); $error\_flags['email'] = true; } else { $error\_flags['email'] = false; } foreach ($error\_messages as $key=\>$error\_message) { $error\_messages[$key] = utf8\_encode($this-\>View()-\>fetch('string:'.$error\_message)); } echo Zend\_Json::encode(array('success'=\>empty($error\_messages), 'error\_flags'=\>$error\_flags, 'error\_messages'=\>$error\_messages)); } public function saveMailAction() { return $this-\>forward('index'); } } [/code] index.tpl [code] {extends file="frontend/index/index.tpl"} {block name="frontend\_index\_content"}
		{include file="frontend/error_message.tpl" error_messages=$error_messages}
		{include file="frontend/mail_fieldset.tpl" update=true form_data=$mail-&gt;form_data error_flags=$mail-&gt;error_flags}
		
		<div class="payment_method register_last"></div>

	
		
		<div class="actions">
			
                        {if $Id}
                            <input id="registerbutton" type="submit" class="right" value="{s name='MailRegisterButtonChange'}{/s}">
                        {else}
                            <input id="registerbutton" type="submit" class="right" value="{s name='MailRegisterButtonSubmit'}{/s}">
                        {/if}
                            <hr class="clear space">
		</div>
		
	</form>

{/block} [/code] mail_fieldset.tpl [code]

{s name=‚MailRegisterHeadline‘}{/s}

{* E-Mail *} {block name=‚frontend_mail_register_fieldset_input_mail‘}

{se name=‚MailRegisterLabelMail‘}{/se}

{/block}
[/code] error_message.tpl {block name='frontend\_mail\_register\_error\_messages'} {if $error\_messages} **{s name='RegisterErrorHeadline'}{/s}** {foreach from=$error\_messages item=errorItem}{$errorItem} {/foreach} {/if} {/block}

Bin jetzt einen großen Schritt weiter. Die Mail wir nun mit meiner Funktion überprüft. Ich hatte zuvor noch keine javascript Datei, das auf die Funktion verweist. Wie schaffe ich jetzt, dass das Feld, in das die Email eingegeben wird eine rote Markierung bekommt? Wo setze ich hier an? Mein jetziger Code: mail.php [code]<?php class Shopware_Controllers_Frontend_Mail extends Enlight_Controller_Action
{

	protected $session;
protected $admin;
protected $system;
protected $post;
protected $error;

/**
 * Calls when the controller will be initialized
 *
 * @return void
 */
public function init()
{
	
            $this->session = Shopware()-\>Session(); $this-\>admin = Shopware()-\>Modules()-\>Admin(); $this-\>system = Shopware()-\>Modules()-\>System(); $this-\>post = $this-\>request-\>getParam('mail'); $this-\>View()-\>addTemplateDir(dirname(\_\_FILE\_\_) . "/../../Views/"); } /\*\* \* Will be called from the dispatcher before an action is processed \* \* @return void \*/ public function preDispatch() { $this-\>View()-\>setScope(Enlight\_Template\_Manager::SCOPE\_PARENT); if(!isset($this-\>View()-\>mail)) { $this-\>View()-\>mail = new ArrayObject(array(), ArrayObject::ARRAY\_AS\_PROPS); } if(!isset($this-\>session['sMail'])) { $this-\>session['sMail'] = new ArrayObject(array(), ArrayObject::ARRAY\_AS\_PROPS); } if(in\_array($this-\>Request()-\>getActionName(), array('ajax\_validate\_mail\_email'))) { Shopware()-\>Plugins()-\>Controller()-\>ViewRenderer()-\>setNoRender(); } } public function indexAction() { $this-\>View()-\>loadTemplate("frontend/index.tpl"); $this-\>mailAction(); } public function mailAction() { if(!isset($this-\>View()-\>mail)) { $this-\>View()-\>mail = new ArrayObject(array(), ArrayObject::ARRAY\_AS\_PROPS); } if(!isset($this-\>View()-\>mail-\>form\_data)) { $this-\>View()-\>mail-\>form\_data = new ArrayObject(array(), ArrayObject::ARRAY\_AS\_PROPS); } } /\*\* \* Checks if the given email is ok. \*/ public function ajaxValidateMailEmailAction() { $error\_flags = array(); $error\_messages = array(); if (empty($this-\>post['email'])) { } elseif (($validator = new Zend\_Validate\_EmailAddress()) && !$validator-\>isValid($this-\>post['email'])) { $error\_messages[] = Shopware()-\>Snippets()-\>getNamespace("frontend\plugins\SwagMail")-\>get('MailAjaxEmailNotValid', 'Please enter a valid mail address.', true); $error\_flags['email'] = true; } else { $error\_flags['email'] = false; } foreach ($error\_messages as $key=\>$error\_message) { $error\_messages[$key] = utf8\_encode($this-\>View()-\>fetch('string:'.$error\_message)); } echo Zend\_Json::encode(array('success'=\>empty($error\_messages), 'error\_flags'=\>$error\_flags, 'error\_messages'=\>$error\_messages)); } public function saveMailAction() { $mail = $this-\>post['email']; die(var\_dump($mail)); return $this-\>forward('index'); } } [/code] Views\frontend\error\_message.tpl [code] {block name='frontend\_mail\_register\_error\_messages'} {if $error\_messages}

{s name=‘RegisterErrorHeadline’}{/s}
{foreach from=$error_messages item=errorItem}{$errorItem}
{/foreach}
{/if} {/block} [/code] Views\frontend\index.tpl [code] {extends file=“frontend/index/index.tpl”} {* * Kein CSS Styling eingebunden *} {* Include javascript *} {block name=‘frontend_index_header_javascript’ append} {/block} {block name=“frontend_index_content”}

		{include file="frontend/error_message.tpl" error_messages=$error_messages}
		{include file="frontend/mail_fieldset.tpl" update=true form_data=$mail-&gt;form_data error_flags=$mail-&gt;error_flags}
		
		<div class="payment_method register_last"></div>

	
		
		<div class="actions">
			
                        {if $Id}
                            <input id="registerbutton" type="submit" class="right" value="{s name='MailRegisterButtonChange'}{/s}">
                        {else}
                            <input id="registerbutton" type="submit" class="right" value="{s name='MailRegisterButtonSubmit'}{/s}">
                        {/if}
                            <hr class="clear space">
		</div>
		
	</form>

{/block} [/code] Views\frontend\mail_fieldset.tpl [code]

{s name=‘MailRegisterHeadline’}{/s}

{* E-Mail *} {block name=‘mail_email’}

{se name=‘MailRegisterLabelMail’}{/se}

{/block}
[/code]

Hatte heute endlich wieder Zeit mich mit der Shopwareprogrammierung und jQuery näher zu bschäftigen. Ich habe es doch tatsächlich hinbekommen :slight_smile: Meine jquery Datei habe ich wie folgt umgeschrieben: [code] jQuery(document).ready(function () { }); (function () { /** Plugin starter */ (document).ready(function () { (’.mail .email input’).mailValidation(); }); })(jQuery); /** * Simple Validation * for Shopware * * Shopware AG © 2010 */ (function () { validate = function (el) { var action; switch (el.attr('id')) { case 'mail\_email': action = 'ajax\_validate\_mail\_email'; break; } if (!el.val()) { setError(el); return; } else if (action) { ajaxValidate(el, action); return; } else { setSuccess(el); return; } }; ajaxValidate = function (el, action) { var data = 'action=' + action + '&' + (’.register form’).serialize(); .ajax({ 'data': data, 'type': 'post', 'dataType': 'json', 'url': .controller.ajax_validate_mail, ‘success’: function (result, data) { if (result && result.error_flags) { for (var error_flag in result.error_flags) { if (result.error_flags[error_flag]) { ('#'+el.attr('id')).removeClass('instyle\_success'); (’#’+el.attr(‘id’)).addClass(‘instyle_error’); } else { ('#'+el.attr('id')).removeClass('instyle\_error'); (’#’+el.attr(‘id’)).addClass(‘instyle_success’); } } } ('#' + action + '\_error').remove(); if (result && result.error\_messages && result.error\_messages.length) { var error\_css = { 'top': el.offset().top - 5, 'left': el.offset().left + el.outerWidth() + 15, 'position': 'absolute', 'z-index': 100 }; var error\_el = (’

').attr(‘id’, action + ‘_error’).addClass(‘error’).prependTo($(‘body’)).css(error_css); for (var error_key in result.error_messages) { if(result.error_messages.length) { var error_message = result.error_messages[error_key]; error_el.append(error_message + ’
'); } } } } }); }; })(jQuery); [/code]

2 „Gefällt mir“

Habe es nicht getestet, aber mal ganz allgemein: vielen Dank fürs Teilen! :slight_smile: