Prevent typing 2 spaces in a row in Text Input - JavaScript

I found a code to prevent all spaces, what if I only want to prevent 2 spaces from being entered together.
Right now anyone can fill the Name text and Message text area with all spaces. :(
Any help would be greatly appreciated.

<script type="text/javascript">

function keyPressed(){
var key = event.keyCode || event.charCode || event.which ;
return key;
}

</script>

<input type="text" onKeyDown="javascript: var keycode = keyPressed(event); if(keycode==32){ return false; }" />


That works fine to stop all spaces but that isn't what I want. I want a real solid form :)
0
give a positive ratinggive a negative rating
04 Jun 2023 at 09:32 PM
Hi,

To avoid submitting a form, that contains only whitespaces in Name or Message field, you can:

Check the text in fields, when user submits the form. You have to remove all the whitespaces from entered text and check if it contains some letters or numbers (or simply check if the field is not empty):

<script type="text/javascript">

function formCheck(){
var v = document.getElementById('name').value;
var e = v.replace(/\s/gm,'');
if(e==""){
alert('The field is empty');
return false;
}
else {
return true;
}
}

</script>
<form name="contact" method="post" onSubmit="javascript: return formCheck();" action="index.php" ><input type="text" id="name" onKeyUp="javascript: checkContent('name');" onBlur="javascript: checkContent('name');" onChange="javascript: checkContent('name');" />
<input type="submit" value="Send" >
</form>

To remove multiple whitespaces in a row, you can use Javascript replace() function.

Replace multiple whitespaces with single whitespace, when user is typing:

<script type="text/javascript">

function checkContent(field){
var v = document.getElementById(field).value;
var e = v.replace(/\s{2,}/gm,' ');
document.getElementById(field).value=e;
}

</script>

<input type="text" id="name" onKeyUp="javascript: checkContent('name');" onBlur="javascript: checkContent('name');" onChange="javascript: checkContent('name');" />

0
give a positive ratinggive a negative rating
11 Jun 2023 at 04:11 PM
Tim
Share on FacebookShare on TwitterShare on LinkedInSend email
x
x
2024 AnswerTabsTermsContact us