I have textbox in which I need validation in such way that it should not allow spaces if textbox is empty. If any values are there in textbox then only it should allow spaces. I am trying below code but not working
var letters = /^[0-9a-zA-Z]+$/;
$("#input1").on("blur ", function() {
function alphanumeric(username) {
if (username.value.match(letters)) {
return true;
} else {
$('#input1').on('keypress', function(e) {
if (e.which == 32)
return false;
});
return false;
}
}
})
I have textbox in which I need validation in such way that it should not allow spaces if textbox is empty. If any values are there in textbox then only it should allow spaces. I am trying below code but not working
var letters = /^[0-9a-zA-Z]+$/;
$("#input1").on("blur ", function() {
function alphanumeric(username) {
if (username.value.match(letters)) {
return true;
} else {
$('#input1').on('keypress', function(e) {
if (e.which == 32)
return false;
});
return false;
}
}
})
Share
Improve this question
edited Apr 10, 2018 at 9:10
Rory McCrossan
338k41 gold badges320 silver badges351 bronze badges
asked Apr 10, 2018 at 9:04
SUNSUN
98317 silver badges39 bronze badges
2
-
1
Don't add event handlers within event handlers. Everytime you
blur
you get anotherkeypress
- just addkeypress
by itself and check the content there. – fdomn-m Commented Apr 10, 2018 at 9:08 -
Is you remove the
$
symbol in your regex, I think it will work the way you want. – bguyl Commented Apr 10, 2018 at 9:20
6 Answers
Reset to default 3if you are using form, you do not need any javascript
<form action='/'>
<input pattern="\s*\S+.*" title="space only is not allowed" required/>
<input type="submit">
</form>
why not just trim?
username.trim()
after that you can just return the result of match.
Add a function on your blur
event that will trim the values which will remove preceding and succeeding whitespace. If the value is empty it will result in ''
.
$("#input1").on("blur", function () {
if($(this).val().trim() === ''){
alert('empty value');
}
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='input1' />
Your Regex seems wrong. You're not allowing spaces characters.
Try this one instead: /\S/
\S
is any non whitespace character.
If you want to start by a character, it will bee /^\S/
.
^
is when you want to start by the following character
$
is when you want to finish by the previous character
You can do it like this:
$(function() {
$('#input1').on('keypress', function(e) {
if ($(this).val() == "")
if (e.which == 32)
return false;
});
});
Online Demo (jsFiddle)
function allowSpace(event) {
var textboxValue = document.getElementById("myTextbox").value;
if (textboxValue.length > 0) {
if (event.keyCode === 32) {
event.preventDefault();
}
}
}