Tips for validating an iFrame in a Symfony form input using a regex

When filling out a publishing form, users have the option to include one or multiple media items by simply copying and pasting <iframe> tags into the designated text fields.

I am seeking a solution to ensure that only valid <iframe> tags are entered into this form by the user.

My attempt at using an @Assert\Regex in my entity below has not been successful, as it validates any data input regardless of its validity.

To create the regex pattern, I utilized the PHP Live Regex online tool which showed that the regex worked correctly.

  • What might be the issue with this regex?
  • Is utilizing @Assert\Regex considered good practice in this scenario?
namespace App\Entity;

use App\Repository\MediaRepository;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity(repositoryClass=MediaRepository::class)
 */
class Media
{
    // ...

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotNull()
     * @Assert\NotBlank()
     * @Assert\Regex(
     *     pattern="/<iframe[^>]*>\s*<\/iframe>/",
     *     message="Please enter a valid iframe tag"
     * )
     */
    private $iframe;

Answer №1

Interestingly, the regex constraint seems to be effective when set up using the FormBuilder:

class MediaType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('iframe',  TextType::class, [
                'constraints' => new Regex([
                    'pattern' => "/^<iframe[^>]*>\s*<\/iframe>/",
                    'message' => "Please enter a valid iFrame tag",
                ])
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver->setDefaults([
            'data_class' => Media::class,
        ]);
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Convert text into a clickable link

Creating a form with numerous text fields, some of which require numerical input. The main goal is to have users enter a tracking number, order number, or any other type of number that, when submitted, will open a new URL in a separate window with the spec ...

Failing to send contact information using JSON in PHP

I attempted to transmit JSON data to PHP for email processing, but encountered an issue where the process veered into the 'else' condition during debugging. Here is the code snippet: HTML <form id="cbp-mc-form" class="cbp-mc-form" method="po ...

Unraveling JSON data retrieved from a MySQL query

After successfully encoding a MySQL result from PHP into JSON, I am now faced with the task of decoding it using JavaScript. Let's assume that my string returned is: [{"0":"x","1":"z"},{"0":"xs","1":"zz"}] I would appreciate some guidance on how to ...

What is the best way to retain the leading zeros when creating a new Number() in JavaScript?

Hey everyone, I'm running into some issues with this specific function. const incrementString = str => { if (!str.match(/[\d+]$/)){ return str += 1 } else{ return str.replace(/[\d+]$/, match => new Number(match) + 1) } ...

No content sent in the request body while implementing fetch

Attempting to send graphql calls from a React component to a PHP server using the fetch method for the first time. The setup involves React JS on the client-side and Symfony 4 on the server-side. Despite indications that data is being sent in the browser ...

What is the best way to display HTML code using Vue syntax that is retrieved from an Axios GET request

I am currently working on a project that involves a Symfony 5 and Vue 3 application. In this setup, a Symfony controller creates a form and provides its HTML through a JSON response. The code snippet below shows how the form HTML is returned as a string: i ...

When PHP echo of json_encode triggers an error, AJAX status 200 will be raised

Despite everything running smoothly in the program below, an AJAX error is triggered: javascript: var data = { email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026f6742656f636b6e2c616d6f">[email protect ...

Is there a way to retrieve a single value using AJAX instead of returning the entire HTML page?

(edited after initial version) I'm facing an issue where my AJAX call is returning the header.php page instead of just the $result value which should be 0 or 1. The AJAX function calls generateTicket.php, where I want to generate tickets only if no o ...

Error message "Unexpected token" occurs when attempting to use JSON.parse on an array generated in PHP

My attempt to AJAX a JSON array is hitting a snag - when I utilize JSON.parse, an error pops up: Uncaught SyntaxError: Unexpected token Take a look at my PHP snippet: $infoJson = array('info' => array()); while($row = mysqli_fetch_array($que ...

An issue arises when using JSON.parse() with regular expression values

I am encountering an issue with parsing a JSON string encoded with PHP 5.2 json_encode(). Here is the JSON string: {"foo":"\\."} Although this JSON string is valid according to jsonlint.com, when using the native JSON.parse() method in Chrome a ...

Easily refresh multiple select options by using the ajax updater function in prototype

After carefully reviewing the documentation for Ajax.Updater(), I noticed that the first argument to the constructor should be container (String | Element) – The DOM element whose contents will be updated as a result of the Ajax request. This can eith ...

Jquery Triggers Failing to Work Following Ajax Request

I have worked on 2 PHP pages, called "booking.php" and "fetch_book_time.php". Within my booking.php (where the jquery trigger is) <?php include ("conn.php"); include ("functions.php"); ?> $(document).ready(function(){ $(".form-group"). ...

Deleting an element from HTML using jQuery

In the midst of creating a system that allows users to construct their own navigation structure, I have encountered a stumbling block. The idea is that when a user lands on the site, they are presented with a list of available topics from which they can ch ...

Please include the document with a name that contains spaces

I am facing an issue where I cannot attach files with spaces in the name. However, when a file with no space in the name is successfully attached. I am using CodeIgniter for this purpose, uploading the file to the server before attaching it. I use the help ...

Indentation differences between PHP and JavaScript

It's interesting to observe the different indentation conventions in various programming languages. Recently, I came across a code snippet from the PHP manual that caught my attention: switch ($i) { case "apple": echo "i is apple"; ...

Unlocking protection: Confirming password strength and security with password indicator and regular expressions for special characters in angular through directive

I have developed an app for password validation using an AngularJS directive. The requirements for the password include at least one special character, one capital letter, one number, and a minimum length of 8 characters. Additionally, I have included a pa ...

Using jQuery to dynamically insert a table row with JSON data into dropdown menus

I'm working on a web form that includes a table where users can add rows. The first row of the table has dependent dropdowns populated with JSON data from an external file. Check out the code snippet below: // Function to add a new row $(function(){ ...

OroCrm is ensuring that Symfony2 profiler seamlessly updates the footer data without triggering a 404 error page within a popup

As a newcomer to OroCrm, I recently installed and configured it on my DEV environment using the app_dev.php entry point. After setting up OroCrm, I immediately noticed the Symfony2 profiler bar appearing at the bottom of the interface. While this was a he ...

utilize jQuery to load webpage with an HTML dropdown element

Querying the Campaigns: // Getting the campaigns $campaigns = $wpdb->get_results( "SELECT * FROM tbl_campaigns ORDER BY campaignID DESC", OBJECT_K ); // Displaying the Cam ...

a common pattern used to substitute website links

I am trying to modify my code that creates HTML links from plain text. While it currently works well, I want to exclude any links that contain .png or .jpg extensions. Does anyone have suggestions on how to adjust the regular expression? var urlPattern ...