4

I am new to magento 2, and I want to apply server side validations, Can anyone please help me, Or suggest me how to apply. I have searched many links for this but i didnot understand. Here is my phtml file (request.phtml)

<div class="wk-mp-design">
    <fieldset class="fieldset info wk-mp-fieldset">
        <legend class="legend">
            <span><?php echo __('Quote Request') ?></span>
        </legend>
  <form action="<?php echo $block->getUrl('quote/contact/save', ['_secure' => $this->getRequest()->isSecure()]) ?>" enctype="multipart/form-data" method="post" id="quote-request" data-form="quote-request" data-mage-init='{"validation":{}}' data-hasrequired="<?php /* @escapeNotVerified */ echo __('* Required Fields') ?>">
            <div class="field required">
                <label class="label"><?php echo __('Full Name') ?>:</label>
                <div class="control">
                        <input type="text" id="full_name" name="full_name" title="Full Name" class="input-text" class="input-text" data-validate="{required:true}"/>
                </div>
            </div>
            <div class="field required">
                <label class="label"><?php echo __('Street Address') ?>:</label>
                <div class="control">
                        <input type="text" id="street_address" name="street_address" title="Street Address" class="input-text" class="input-text" class="input-text" data-validate="{required:true}" />
                </div>
            </div>
            <div class="field required">
                <label class="label"><?php echo __('Suburb') ?>:</label>
                <div class="control">
                        <input type="text" id="district" name="district" title="Suburb" class="input-text" class="input-text" data-validate="{required:true}"/>
                </div>
            </div>
            <div class="field required">
                <label class="label"><?php echo __('Post Code') ?>:</label>
                <div class="control">
                        <input type="text" id="post_code" name="post_code" title="Post Code" class="input-text" class="input-text" class="input-text" class="input-text" data-validate="{required:true}"  />
                </div>
            </div>
            <div class="field required">
                <label class="label"><?php echo __('Phone Number') ?>:</label>
                <div class="control">
                        <input type="text" id="phone_number" name="phone_number" title="Phone Number" class="input-text" class="input-text" class="input-text" class="input-text" data-validate="{required:true, 'validate-number':true}"/>
                </div>
            </div>
            <div class="field required">
                <label class="label"><?php echo __('Email Address') ?>:</label>
                <div class="control">
                        <input type="email" id="email" name="email" title="Email Address" class="input-text" class="input-text" class="input-text" class="input-text" class="input-text" data-validate="{required:true, 'validate-email':true}"/>
                </div>
            </div>
            <div class="field required">
                <?php echo __("Please attach any photo's that will help describe your job.(Max 5 images/3Mb of data. JPGS Only)") ?>
                <div class="control">
                        <input type="file" id="attachment" name="attachment"  title="Attachment" class="input-text" class="input-text" data-validate="{required:true}"/>
                </div>
            </div>
            <div class="field required">
                <div class="control">
                    <textarea name="description" id="description" class="input-text" class="input-text" data-validate="{required:true}"></textarea>
                </div>
            </div>
              <button class="button wk-mp-btn" title="<?php echo __('Submit') ?>" type="submit" id="submit-btn">
                <span><span><?php echo __('Submit') ?></span></span>
            </button>
              <button class="button wk-mp-btn" title="<?php echo __('Reset') ?>" >
                <span><span><?php echo __('Reset') ?></span></span>
            </button>
        </form>
    </fieldset>
</div>
<script type="text/x-magento-init">
    {
        "#quote-request": {
            "validation": {}
        }
    }
</script>

I have applied client side validations, but I am not getting how to apply server side validations.

1 Answer 1

6

You can use server side validation as below:

if (!\Zend_Validate::is(trim($post['name']), 'NotEmpty')) {
      $error = true;
}
if (!\Zend_Validate::is(trim($post['comment']), 'NotEmpty')) {
      $error = true;
}
if (!\Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
      $error = true;
 }
 if (\Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
      $error = true;
 }

For more information you can check below contact post controller code:

<?php
/**
 *
 * Copyright © 2016 Magento. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Magento\Contact\Controller\Index;

class Post extends \Magento\Contact\Controller\Index
{
    /**
     * Post user question
     *
     * @return void
     * @throws \Exception
     */
    public function execute()
    {
        $post = $this->getRequest()->getPostValue();
        if (!$post) {
            $this->_redirect('*/*/');
            return;
        }

        $this->inlineTranslation->suspend();
        try {
            $postObject = new \Magento\Framework\DataObject();
            $postObject->setData($post);

            $error = false;

            if (!\Zend_Validate::is(trim($post['name']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['comment']), 'NotEmpty')) {
                $error = true;
            }
            if (!\Zend_Validate::is(trim($post['email']), 'EmailAddress')) {
                $error = true;
            }
            if (\Zend_Validate::is(trim($post['hideit']), 'NotEmpty')) {
                $error = true;
            }
            if ($error) {
                throw new \Exception();
            }

            $storeScope = \Magento\Store\Model\ScopeInterface::SCOPE_STORE;
            $transport = $this->_transportBuilder
                ->setTemplateIdentifier($this->scopeConfig->getValue(self::XML_PATH_EMAIL_TEMPLATE, $storeScope))
                ->setTemplateOptions(
                    [
                        'area' => \Magento\Backend\App\Area\FrontNameResolver::AREA_CODE,
                        'store' => \Magento\Store\Model\Store::DEFAULT_STORE_ID,
                    ]
                )
                ->setTemplateVars(['data' => $postObject])
                ->setFrom($this->scopeConfig->getValue(self::XML_PATH_EMAIL_SENDER, $storeScope))
                ->addTo($this->scopeConfig->getValue(self::XML_PATH_EMAIL_RECIPIENT, $storeScope))
                ->setReplyTo($post['email'])
                ->getTransport();

            $transport->sendMessage();
            $this->inlineTranslation->resume();
            $this->messageManager->addSuccessMessage(
                __('Thanks for contacting us with your comments and questions. We\'ll respond to you very soon.')
            );
            $this->_redirect('contact/index');
            return;
        } catch (\Exception $e) {
            $this->inlineTranslation->resume();
            $this->messageManager->addErrorMessage(
                __('We can\'t process your request right now. Sorry, that\'s all we know.')
            );
            $this->_redirect('contact/index');
            return;
        }
    }
}
1
  • You do not log Exception in order to have exception stack trace ? Feb 22, 2017 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.