I want to validate or ensure that user inputs just one word in my HTML text field using JavaScript. Any help?
Asked
Active
Viewed 641 times
0
-
maybe this link can help you http://stackoverflow.com/questions/18679576/counting-words-in-string – Omid Behrouzi Jul 25 '15 at 08:23
2 Answers
1
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

Sagar
- 642
- 3
- 14
1
<!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>

Community
- 1
- 1

Shree Ram Neupane
- 407
- 5
- 16