【问题标题】:Validation on a pre-populated form field验证预填充的表单字段
【发布时间】:2012-11-14 06:15:18
【问题描述】:

要在symfony2 的表单字段中设置默认值,我使用rel 属性与jQuery 相结合,正如here 的精彩解释:

    $builder->add('title', 'text', array(
        'attr'=> array(
            'class'=>'prepopulate',
            'rel'=>'Enter a title here...',
        )
    ));

这非常有效,并提供以下内容:



如您所见,该字段已预先填充“在此处输入标题...”。如果我按原样验证表单,则不会在插入默认值时进行验证(这是有道理的)。

我想确保用户自定义此字段,而不只是提交带有默认值的表单...

有没有办法检查该字段是否与 rel 属性的值相同?

【问题讨论】:

    标签: symfony symfony-forms symfony-2.1


    【解决方案1】:

    嗯……

    您可以在实体的注释中尝试此操作:

    @Assert\Regex("/^(?!Enter a title here\.\.\.)/")
    

    甚至更好:

    /**
     * @Assert\Regex(
     *     pattern="/^Enter a title here\.\.\.$/",
     *     match=false,
     *     message="Please enter a title."
     * )
     */
    

    【讨论】:

    • +1。绝招@keyboardSmasher!这具有为每个字段重复代码的缺点。但你知道,它有效,所以很好!做得好!如果您有兴趣,我建议使用 javascript 解决方案,因为它具有迭代每个表单字段的主要优势。感谢您的帮助!
    【解决方案2】:

    我们可以在客户端执行此操作,并将 rel 属性与提交的数据进行比较。如果值相同,我们清除对象:

    $(function() {
        // When we submit the form
        $('form').submit(function() {
    
            //iterate over all the elements of the class "prepopulate"
            jQuery('.prepopulate').each(function(){
    
                //compare the values submitted vs rel attribute
                if( jQuery(this).val() == jQuery(this).attr('rel'))
                    jQuery(this).val('');
            });
            return true; 
        });
    });
    

    【讨论】:

    • 是的,这将在客户端完成。我以为你想为那些在浏览器中关闭了 javascript 的 nut-jobs 提供服务器端选项。大声笑但现在我想一想,如果他们的javascript被关闭,他们将不会有预先填充的字段。所以,你赢了。 :)
    猜你喜欢
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 2017-05-21
    • 1970-01-01
    • 2013-05-13
    相关资源
    最近更新 更多