views:

55

answers:

2

Hi All,

Please, I'm a newbie in PHP, and created my web site, with a text form, i can verify with JQuery if the txt form is empty or not with the following code :

    $(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();
        }


    }

How to verify that the txt form is not empty, and there is not only white-spaces in the field, because here after submitting many white-spaces, the text is posted to the action page.

Sorry for my bad english.

Thanks in advance.

A: 

Replace this line

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

With this line

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

$.trim removes unnecessary spaces so it will get trimmed to "" if someone enters only white space.

Marko
Thanks for the solution, Trim function works great ;)
McShark
A: 

[EDITED]

for the checking:

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

must be

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

or

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

or

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

This means, that the input must contain atleast 1 non-space character

sheeks06
It might be better to use `if(! /\S/.match(txtform))` for the second check, instead of doing a replace operation.
Amber
I've removed the first part of your answer, since val() is actually **correct**.
Marko
replace and match method not working, the Google Chrome JS console return : Uncaught TypeError: Object /\S/ has no method 'match'
McShark
Your function removes all spaces, not only the leading and trailing one. The following should be used instead: `if(txtform.replace(/^\s+/g, "").replace(/\s+$/g) == '')` (`.val()` always returns a string, so checking for null is silly)
Lekensteyn
that's what already jQuery.trim(str) does. The remove all spaces is ok since if there are no non-space character in the input, the result will be true. so if we say, " a a " = false. "a a" = false. " a " = false. " " = true. " " = true. "" = true
sheeks06