php Symfony2 禁用 HTML5 表单验证
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10142509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Symfony2 disable HTML5 form validation
提问by user1331787
I want to validate my form using server side validation only. However, if the browser supports HTML5 it validates using the HTML5 attributes added to the form by symfony2 so I need to prevent HTML5 validation.
我只想使用服务器端验证来验证我的表单。但是,如果浏览器支持 HTML5,它会使用 symfony2 添加到表单的 HTML5 属性进行验证,因此我需要阻止 HTML5 验证。
回答by Ondrej Slinták
Just add novalidateto your <form>tag:
只需添加novalidate到您的<form>标签:
<form novalidate>
If you are rendering the form in TWIG, you can use following.
如果您在 TWIG 中渲染表单,则可以使用以下内容。
{{ form(form, {'attr': {'novalidate': 'novalidate'}}) }}
回答by d3uter
I know its old question but with SF2.6 in FormType, you can do:
我知道它的老问题,但是使用 FormType 中的 SF2.6,您可以执行以下操作:
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'attr'=>array('novalidate'=>'novalidate')
));
}
回答by LorenzSchaef
While googling for a solution to this I found one, that seems the most elegant if you want to disable html5 validation in your whole app, so I thought i'd share it here. Credits go to the author of this blog article.
在谷歌搜索解决方案时,我找到了一个,如果您想在整个应用程序中禁用 html5 验证,这似乎是最优雅的,所以我想我会在这里分享它。致谢此博客文章的作者。
The idea is to create an extension for the "form" form type like this:
这个想法是为“表单”表单类型创建一个扩展,如下所示:
<?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';
}
}
?>
Then you just register it in your services.yml like this:
然后你只需像这样在 services.yml 中注册它:
app.no_validation_form_extension:
class: AppBundle\Form\Extension\NoValidateExtension
tags:
- {name: form.type_extension, alias: form}
and you're done. All your forms automatically have a novalidateattribute now.
你就完成了。您的所有表单novalidate现在都会自动拥有一个属性。
Symfony 3.3
Symfony 3.3
As of Symfony 3.3 the configuration is slightly different, but still possible.
从 Symfony 3.3 开始,配置略有不同,但仍然可能。
Slight update to the getExtendedTypemethod to return the FormTypeclass.
稍微更新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;
}
}
Plus some a minor addition of the extended_typetag, which is now required in your service declaration:
加上一些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}
回答by DevWL
Alternatively if for some reason you don't want to do it in twig as in the answer above...
或者,如果由于某种原因你不想像上面的答案那样在树枝上做......
{{ form(form, {'attr': {'novalidate': 'novalidate'}}) }}
{{ form(form, {'attr': {'novalidate': 'novalidate'}}) }}
or you create your from manually with createFormBuilder then you could simply use createFormBuilder as a second parameter to define form attribute:
或者您使用 createFormBuilder 从手动创建,那么您可以简单地使用 createFormBuilder 作为第二个参数来定义表单属性:
//someAction
$form = $this->createFormBuilder(null, ['attr'=>['novalidate'=>'novalidate']])
->add(...)
->add(...)
->add(...)
->getFrom();
return $this->render("-----:----:----.html.twig", [
'form'=>$form->createView()
]);
回答by Joseph Astrahan
If you are using Symfony 3 (or 2) and want to turn off validation for a specific field only you can do this.
如果您正在使用 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();
In this sample form notice the array('required' => false), you can add this to any element that you want to disable validation for without disabling validation for the others. Very useful if you want to temporarily disable only one element instead of the entire form.
在此示例表单中,注意array('required' => false),您可以将其添加到要禁用验证的任何元素,而不禁用其他元素的验证。如果您只想暂时禁用一个元素而不是整个表单,则非常有用。
Note this ONLY disables the HTML5 validation!This does not disable server side validation.
请注意,这只会禁用 HTML5 验证!这不会禁用服务器端验证。
Reference: http://symfony.com/doc/current/book/forms.html#field-type-options
参考:http: //symfony.com/doc/current/book/forms.html#field-type-options
回答by Jon Winstanley
If you actually need to remove the validation attributes (if you are using a validation library want to keep all of your validation constraints in one place for example), you can overwrite the widget_attributes block in twig.
如果您确实需要删除验证属性(例如,如果您使用验证库想要将所有验证约束保留在一个地方),您可以覆盖 twig 中的 widget_attributes 块。
If you are already using custom form templates in app/Resources/views/form.html.twig for example (and have enabled it in your config.yml) you can just add a block for
例如,如果您已经在 app/Resources/views/form.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 %}
All I have done here is remove the attributes related to validation:
我在这里所做的就是删除与验证相关的属性:
{% if required %} required="required"{% endif %}{% if max_length %} maxlength="{{ max_length }}"{% endif %}{% if pattern %} pattern="{{ pattern }}"{% endif %}
{% if required %} required="required"{% endif %}{% if max_length %} maxlength="{{ max_length }}"{% endif %}{% if pattern %} pattern="{{ pattern }} “{% 万一 %}
回答by Saman Mohamadi
To disable Regex validation for specific field using formType class:
要使用 formType 类禁用特定字段的正则表达式验证:
->add('foo',null,array=>('attr'=>('pattern'=>'/[^~,]/'))
回答by JohnSmith
Use form theming:
使用表单主题:
First create form theme template, e.g app/Resources/views/form/fields.html.twig:
首先创建表单主题模板,例如 app/Resources/views/form/fields.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 %}
Then use that form theme in your template:
然后在模板中使用该表单主题:
{% form_theme form with 'form/fields.html.twig' %}
{{ form_start(form) }} <-- now renders with novalidate attribute
...
{{ form_end(form) }}
Or, apply theme globally (app/config/config.yml):
或者,全局应用主题 (app/config/config.yml):
twig:
form_themes:
- ':form/fields.html.twig'

