Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    Jul 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts

    HTML Form Validation two words

    Hello.
    I want to validate via javascript an input text box. What i want is to have at least two words ( not letters ).

    At this moment i did validation to detect if the input is empy:

    <script>
    function validateForm()
    {
    var x=document.forms["myForm"]["s"].value
    if (x==null || x=="")
    {
    alert("Nu ati introdus nimic.");
    return false;
    }
    }
    </script>

    But how to validate to have at leat two words inside my input area.

    Thank you.

    Here is my form:

    <form name="myForm" method="get" id="searchform" onsubmit="return validateForm()" action="<?php bloginfo('home'); ?>/">
    <div><input type="text" value="" name="s" id="s" />
    <input type="hidden" name="cat" value="19" />
    <input type="submit" id="searchsubmit" value="Cauta document" />
    </div>
    </form>

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    26,603
    Thanks
    80
    Thanked 4,500 Times in 4,464 Posts
    Maybe like this:
    Code:
    function validateForm(form)
    {
        var x = form.s.value;
        x = x.replace(/^\s+/,"").replace(/\s+$/,""); // this trims off leading & trailing spaces
        x = x.replace(/\s{2,}/," "); // this gets rid of multiple spaces
        var words = x.split(" "); // split the result apart on any remaining space
        if ( words.length < 2 ) 
        {
            alert("Must enter at least 2 words");
            return false;
        }
        return true; // do not forget this
    }
    
    ...
    <form method="get" onsubmit="return validateForm(this)" action="<?php bloginfo('home'); ?>/">
    ...
    There is no reason to give your <form> either a name or id.

    And there is usually no reason to give form fields an id.

  • #3
    New to the CF scene
    Join Date
    Jul 2011
    Posts
    2
    Thanks
    0
    Thanked 0 Times in 0 Posts
    unfortunately does not work.

    Another option if you can ....

    Thank you

  • #4
    Regular Coder low tech's Avatar
    Join Date
    Dec 2009
    Posts
    852
    Thanks
    173
    Thanked 94 Times in 94 Posts
    Hi

    unfortunately does not work.
    Sure it works.


    What i want is to have at least two words ( not letters ).
    In your opinion, what would be the minimum amount of letters contained in any two meaningful words you might expect someone to input that you will accept?



    LT


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •