Reputation:
I have 3 input fields and I need a short jquery code to disallow spaces in them.
<input id='email' type='email' name='email' />
<input id='username' type='text' name='username' />
<input id='pwd' type='password' name='pwd' />
Upvotes: 1
Views: 161
Reputation: 1598
This is the first solution that the user cannot bypass by pasting in a value from their clipboard -- something user's do a lot of.
This is the first solution that the user cannot bypass because they are using a browser extension to fill out logins/forms for them.
Since you mention jQuery what about form validation with Validate Plugin?
Or if you want simple validation how about using an submit event to test it.
$('form').on('submit', function () {
var spaceTest = new RegExp('^[^ \t\r\n\v\f]*$');
//loop through your desired form elements
$(this).find('.disallow').each(function () {
var $this = $(this),
m = spaceTest.exec($this.val());
// if it fails your test
if (m === null) {
// reject
} else {
// accept
}
});
});
Upvotes: 0
Reputation: 73906
Try this:
$('input').keypress(function (e) {
// For detecting charCode, the following is the best cross-browser approach
var charCode = e.which || e.keyCode;
if (charCode === 32) {
// the default action of the event will not be triggered.
e.preventDefault();
}
});
This will disallow spaces in all the inputs. If you want to disallow spaces on only three of the inputs above or more, just add a class to all of them like myClass
and call the function like:
$('.myClass').keypress(function (e) {
Upvotes: 1
Reputation: 392
Firstly, add a class to the 3 input tags
<input id='email' class='disallow' type='email' name='email' />
<input id='username' class='disallow' type='text' name='username' />
<input id='pwd' class='disallow' type='password' name='pwd' />
Here is the jQuery:-
$(document).ready(function() {
$('.disallow').keypress(function(e) {
if(e.which === 32) {
return false;
}
});
});
Upvotes: 1