【问题标题】:How to verify a form is empty ? PHP or JS如何验证表单是否为空? PHP 或 JS
【发布时间】:2010-09-15 14:23:33
【问题描述】:

拜托,我是 PHP 的新手,并创建了我的网站,使用文本表单,我可以使用 JQuery 验证 txt 表单是否为空,使用以下代码:

    $(document).ready(function()
    {
        $('#formLike').ajaxForm({                       
                target:         '#content',
                beforeSubmit:   validateForm
        }); 

        //hide error containers
        $("#txtform_error").hide();

    });

    function validateForm()
    {
        $("#txtform_error").empty().hide();

        var txtform         = $("#txtform").val();
        var errors              = 0;

        if (txtform == null || txtform == ''  || txtform == ' ')
        {
            $("#txtform_error").show().append("Please Write a Message Before Clicking : Like It");
            document.formLike.txtform.focus();
        }
        else
        {
        document.formLike.submit();
        }


    }

如何验证txt表单不为空,并且字段中不仅有空格,因为这里提交了很多空格后,文本被发布到操作页面。

对不起,我的英语不好。

提前致谢。

【问题讨论】:

    标签: php javascript jquery html forms


    【解决方案1】:

    替换此行

    if (txtform == null || txtform == ''  || txtform == ' ')
    

    用这条线

    if ($.trim(txtform) == "")
    

    $.trim 删除不必要的空格,因此如果有人只输入空格,它将被修剪为“”。

    【讨论】:

      【解决方案2】:

      [编辑]

      检查:

      if (txtform == null || txtform == ''  || txtform == ' ')
      

      必须

      if (!txtform || txtform.replace(/\s/g, '') == '') 
      

      if (!txtform || !txtform.replace(/\s/g, '')) 
      

      if (!txtform || !jQuery.trim(txtform)) //trimmed only
      

      这意味着,输入必须包含至少 1 个非空格字符

      【讨论】:

      • 最好使用if(! /\S/.match(txtform)) 进行第二次检查,而不是进行替换操作。
      • 我已经删除了你答案的第一部分,因为 val() 实际上是正确
      • 替换和匹配方法不起作用,Google Chrome JS 控制台返回:Uncaught TypeError: Object /\S/ has no method 'match'
      • 您的函数会删除所有空格,而不仅仅是前导空格和尾随空格。应该使用以下代码:if(txtform.replace(/^\s+/g, "").replace(/\s+$/g) == '').val() 总是返回一个字符串,所以检查 null 是愚蠢的)
      • 这就是 jQuery.trim(str) 所做的。删除所有空格是可以的,因为如果输入中没有非空格字符,结果将为真。因此,如果我们说“ a a” = false。 “一个”=假。 “一”=假。 " " = 真。 " " = 真。 "" = 真
      猜你喜欢
      • 2011-11-04
      • 1970-01-01
      • 2012-06-28
      • 1970-01-01
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多