Reputation: 79
I have validated input fields to check for empty fields. Later I noticed someone can just enter white space and submit the form. Can someone help me remove white space before text but accept space in the middle of the text of the input. I tried using this but will not allow white space in the middle of the input
$('input').keyup(function() {
$(this).val($(this).val().replace(/\s+/g, ''));
});
How do I fix this?
Upvotes: 1
Views: 3959
Reputation: 11733
First of all, nothing to do with your question, but you should be validating the field only when the user is trying to submit your form, so, you should use the HTMLFormElement's submit
event.
Second, you should be revalidating your form in your backend, because people can just change things client side, via console/debug etc, and that's a really security matter.
Third, about your question itself: You can use the String.prototype.trim
method, as follows:
$('input').keyup(function() {
$(this).val($(this).val().trim());
});
Upvotes: 2
Reputation: 1280
You need trim method. Short example:
var str = " Hello World! ";
alert(str.trim());
The alert will display Hello World without white spaces.
More information here: http://www.w3schools.com/jsref/jsref_trim_string.asp
Upvotes: 0
Reputation: 1511
.trim() removes leading and trailing spaces leaving ones in the middle unmolested.
Upvotes: 0