I have an username input field and trying to prevent user fill them with white spaces.
<input type="text" name="username" />
i do this and whitespace isn't blocked
var
field = document.querySelector('[name="username"]');
field.addEventListener('keypress', function ( event ) {
var
key = event.keyCode;
return (key !== 32);
});
Use event.preventDefault to prevent its default behavior.
var field = document.querySelector('[name="username"]');
field.addEventListener('keypress', function ( event ) {
var key = event.keyCode;
if (key === 32) {
event.preventDefault();
}
});
<input type="text" name="username" />
If you want to use the return false;
, then you should use the onkeypress
of the input instead, jsfiddle
field.onkeypress = function(e) {
var key = e.keyCode;
return (key !== 32);
};
In case anyone needs this to be done which will replace all whitespace automatically and will not allow user to put space and will force them to put username without space even then copy paste . Here is the code.
<script type="text/javascript">
var field = document.querySelector('[name="username"]');
field.addEventListener('keyup', function ( event ) {
var userName = field.value;
userName = userName.replace(/\s/g, '');
field.value = userName;
});
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With