Symfony2禁用HTML5表单验证


Symfony2 disable HTML5 form validation

我想仅使用服务器端验证来验证我的表单。但是,如果浏览器支持 HTML5,它会使用 symfony2 添加到表单中的 HTML5 属性进行验证,所以我需要阻止 HTML5 验证。

只需将novalidate添加到您的<form>标签中:

<form novalidate>

如果要在 TWIG 中呈现表单,则可以使用以下方法。

{{ form(form, {'attr': {'novalidate': 'novalidate'}}) }}
我知道

它的老问题,但是使用FormType中的SF2.6,您可以执行以下操作:

/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'attr'=>array('novalidate'=>'novalidate')
    ));
}

在谷歌搜索解决方案时,我发现了一个,如果您想在整个应用程序中禁用 html5 验证,这似乎是最优雅的,所以我想我会在这里分享它。学分归本博客文章的作者所有。

这个想法是为"表单"表单类型创建一个扩展,如下所示:

<?php
// src/AppBundle/Form/Extension/NoValidateExtension.php
namespace AppBundle'Form'Extension;
use Symfony'Component'Form'AbstractTypeExtension;
use Symfony'Component'Form'FormInterface;
use Symfony'Component'Form'FormView;

class NoValidateExtension extends AbstractTypeExtension
{
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['attr'] = array_merge($view->vars['attr'], [
            'novalidate' => 'novalidate',
        ]);
    }
    public function getExtendedType()
    {
        return 'form';
    }
}
?>

然后,您只需像这样在services.yml中注册它:

app.no_validation_form_extension:
    class: AppBundle'Form'Extension'NoValidateExtension
    tags:
        - {name: form.type_extension, alias: form}

大功告成。您的所有表单现在都自动具有novalidate属性。

Symfony 3.3

从Symfony 3.3开始,配置略有不同,但仍然是可能的。

getExtendedType 方法稍作更新以返回 FormType 类。

// src/AppBundle/Form/Extension/NoValidateExtension.php
namespace AppBundle'Form'Extension;
use Symfony'Component'Form'AbstractTypeExtension;
use Symfony'Component'Form'FormInterface;
use Symfony'Component'Form'FormView;
use Symfony'Component'Form'Extension'Core'Type'FormType;
class NoValidateExtension extends AbstractTypeExtension
{
    public function buildView(FormView $view, FormInterface $form, array $options)
    {
        $view->vars['attr'] = array_merge($view->vars['attr'], [
            'novalidate' => 'novalidate',
        ]);
    }
    public function getExtendedType()
    {
        return FormType::class;
    }
}

再加上一些 extended_type 标记的少量添加,现在在您的服务声明中需要:

app.no_validation_form_extension:
    class: AppBundle'Form'Extension'NoValidateExtension
    tags:
        - {name: form.type_extension, alias: form, extended_type: Symfony'Component'Form'Extension'Core'Type'FormType}
或者,

如果由于某种原因您不想像上面的答案那样在树枝上执行此操作......

{

{ form(form, {'attr': {'novalidate': 'novalidate'

}}) }}

或者您使用createFormBuilder手动创建,然后您可以简单地使用createFormBuilder作为第二个参数来定义表单属性:

//someAction
$form = $this->createFormBuilder(null, ['attr'=>['novalidate'=>'novalidate']])
->add(...)
->add(...)
->add(...)
->getFrom();
return $this->render("-----:----:----.html.twig", [
    'form'=>$form->createView()
]);

如果您使用的是Symfony 3(或2),并且只想关闭特定字段的验证,则可以执行此操作。

$form = $this->createFormBuilder($task)
            ->add('task', TextType::class, array('required' => false))
            ->add('dueDate', DateType::class)
            ->add('save', SubmitType::class, array('label' => 'Create Task'))
            ->add('saveAndAdd', SubmitType::class, array('label' => 'Save and Add'))
            ->getForm();

在此示例表单中,请注意数组('required' => false),您可以将其添加到要禁用验证的任何元素中,而无需禁用对其他元素的验证。 如果您只想暂时禁用一个元素而不是整个表单,则非常有用。

请注意,这只会禁用HTML5验证!这不会禁用服务器端验证。

参考: http://symfony.com/doc/current/book/forms.html#field-type-options

如果您确实需要删除验证属性(例如,如果您使用的是验证库,希望将所有验证约束保存在一个地方),则可以覆盖 twig 中的widget_attributes块。

例如,如果您已经在应用程序/资源/视图/表单.html.twig 中使用自定义表单模板(并且已在 config.yml 中启用了它),您只需添加一个块

{% block widget_attributes %}
{% spaceless %}
    id="{{ id }}" name="{{ full_name }}"{% if read_only %} readonly="readonly"{% endif %}{% if disabled %} disabled="disabled"{% endif %}
    {% for attrname, attrvalue in attr %}{% if attrname in ['placeholder', 'title'] %}{{ attrname }}="{{ attrvalue|trans({}, translation_domain) }}" {% else %}{{ attrname }}="{{ attrvalue }}" {% endif %}{% endfor %}
{% endspaceless %}
{% endblock widget_attributes %}

我在这里所做的只是删除与验证相关的属性:

{% if required %} required="required"{% endif %}{% if max_length %} maxlength="{{ max_length }}"{% endif %}{% if pattern %}

pattern="{{ pattern }}"{% endif %}

要使用 formType 类禁用特定字段的正则表达式验证:

->add('foo',null,array=>('attr'=>('pattern'=>'/[^~,]/'))

使用表单主题:

首先创建表单主题模板,例如应用程序/资源/视图/表单/字段.html.twig:

{% extends 'form_div_layout.html.twig' %}{# or some other base layout #}
{% block form_start %}
    {% if attr.novalidate is not defined %}
        {% set attr = attr|merge({'novalidate':'novalidate'}) %}
    {% endif %}
    {{ parent() }}
{% endblock %}

然后在模板中使用该表单主题:

{% form_theme form with 'form/fields.html.twig' %}
{{ form_start(form) }} <-- now renders with novalidate attribute
...
{{ form_end(form) }}

或者,全局应用主题(app/config/config.yml):

twig:
    form_themes:
        - ':form/fields.html.twig'