eniac05
eniac05

Reputation: 491

how to validate html text field using java script to ensure no more than one word contain in text field

I want to validate or ensure that user inputs just one word in my HTML text field using JavaScript. Any help?

Upvotes: 0

Views: 702

Answers (2)

Shree Ram Neupane
Shree Ram Neupane

Reputation: 407

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<form action="" method='post'>
        <input type='text' name='my-field' id='my-field' />
        <input type='submit' name='submit' value='Submit' />
</form>

<script>
    var element = document.getElementById('my-field');

    element.onblur = function() {
        var value = element.value.trim();

        if (value.indexOf(' ') > -1 ) {
            alert('do not use space');
            element.focus();
        }
     }
</script>
</body>
</html>

And, with out using alert refer.

Upvotes: 1

Sagar
Sagar

Reputation: 647

Suppose if user string is say in javascript variable

var input; // store user input

then use string split function on white space

var len =input.split(" ");

then if lenght of array 'len' is greater than 1 that means user entered more than one word.

if(len.length > 1)
// print message

Upvotes: 1

Related Questions