webrider
webrider

Reputation: 95

checking space between text in javascript

I want to check the gap between two or more words, i have given as an input, in a text box. If there had any space, then i want to alert user that no space is allowing. I can check the existence of text simply using "if else" statement. But can't do the desired stuff in this way. My code is given below :

<script type="text/javascript">

function checkForm()

    {

        var cName=document.getElementById("cName").value;
        var cEmail=document.getElementById("cEmail").value;

        if(cName.length<1)

        {
            alert("Please enter both informations");
            return false;
        }

        if(cEmail.length<1)
        {
            alert("Please enter your email");
            return false;
        }

        else
        {
            return true;
        }

    }

        Name : <input type="text" id="cName" name="cName"/>
        <br/>
        <br/>
        Email : <input type="text" id="cEmail" name="cEmail"/>
        <br/>
        <br/>
        <input type="submit" value="Go!"/>

        </form>

Upvotes: 1

Views: 9368

Answers (2)

Rashmi Kant
Rashmi Kant

Reputation: 159

your question not very clear , but i hope you want to count your words you can use the following code to split a text and by using the length property you count the word

var b = document.getElementById("cName").value;
var temp = new Array();
    temp = b.split(' ');
var count= temp.length;

and if you want to validate your name field that should not use any space

if ( ^[A-Za-z]$.test(document.getElementById("cName").value) ) {
    // your code;
}

if ( document.getElementById("cName").value.indexOf(' ') > 0 ) {
    alert('space found');
}

Upvotes: 1

Some Guy
Some Guy

Reputation: 16190

Just use the match() method of strings. For example:

'Spaces here'.match(' ');

That returns true.

'Nospace'.match(' ');

That returns false.

So for what you want, just use something like this:

if(cName.match(' ')){
   alert('Spaces found!');
   return false;
}

Demo

Upvotes: 6

Related Questions