1

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?

James Favour
  • 97
  • 1
  • 2
  • 9
  • http://stackoverflow.com/questions/498970/trim-string-in-javascript – Lee Taylor Sep 26 '15 at 20:42
  • 2
    regardless of what you do with javascript you ***must*** validate/santize data server side...anyone can bypass script in browser – charlietfl Sep 26 '15 at 20:42
  • I know how to use PHP to do that. I just need the JS script to remove the white space at the very beginng of text and also be able to allow white space in the middle of the data...e.g if you want to enter full name, you might want to add space to separate your full name. e.g James Oduro – James Favour Sep 26 '15 at 20:48

4 Answers4

2

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());
});
Buzinas
  • 11,597
  • 2
  • 36
  • 58
  • I still have the same proble... the first space is removed but assuming in an input field like to enter a full name and I will need white space in the middle of the name to separate the name...because of the trim() , i can't add space in the middle...any help on that? – James Favour Sep 26 '15 at 21:04
  • @JamesFavour Instead of using `keyup` you could be using `change` event. – Buzinas Sep 28 '15 at 15:58
  • @JamesFavour e.g: `$('input').change(function() {` – Buzinas Sep 28 '15 at 15:58
0

.trim() removes leading and trailing spaces leaving ones in the middle unmolested.

Rothrock
  • 1,413
  • 2
  • 16
  • 39
0

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

cadi2108
  • 1,280
  • 6
  • 19
  • 43
0

you can use String trim() Method Reference is here

Bouzaid
  • 66
  • 8