简体   繁体   中英

How to remove one or more white space before a text in the input field

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?

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());
});

.trim()删除前导和尾随空格,使中间的空格不受干扰。

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

您可以在这里使用String trim()方法参考

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM