Reputation: 491
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
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
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