Maksim Senko
Maksim Senko

Reputation: 71

Trim white spaces of value in input

Help needed for a newbie. I'm having a hard time deleting white spaces from input in the submit form. Here's the way I tried to do it:

var usernameInput = document.querySelector('.setup-user-name');
var newValue = usernameInput.value.trim();
usernameInput.value = newValue;

After that form should go through validation like that:

usernameInput.addEventListener('invalid', function () {
  if (usernameInput.validity.tooShort) {
    usernameInput.setCustomValidity('Имя должно состоять минимум из 2-х 
символов');
  } else if (usernameInput.validity.valueMissing) {
    usernameInput.setCustomValidity('Обязательное поле');
  } else {
    usernameInput.setCustomValidity('');
  }
});

Even though I use the trim method I'm still able to submit the form with spaces in the input.

Upvotes: 3

Views: 14264

Answers (2)

Gershom Maes
Gershom Maes

Reputation: 8150

You can prevent users from entering usernames containing leading or trailing spaces by using the html pattern attribute and using regex to define what an acceptable username looks like:

<p>Try entering a value with leading and/or trailing spaces</p>
<p>If the form disappears that means the value was accepted</p>
<form enctype"...">
  <input class="setup-user-name" placeholder="username" pattern="^[^ ].+[^ ]$" />
  <input type="submit" value="submit" />
</form>

You'll note the regex I used here is:

^[^ ].+[^ ]$

  • The initial carat symbol (^) means "the beginning of the string".
  • The sequence [^ ] means "any character but a space"
  • The sequence .+ means "anything at all; minimum 1 character"
  • The sequence [^ ] again means "any character but a space"
  • The final $ symbol means "the end of the string"

This regex defines an "acceptable" value as one which doesn't have a space directly after the beginning of the string, or directly before the end of the string.

Upvotes: 7

Sahil Raj Thapa
Sahil Raj Thapa

Reputation: 2483

Javascript trim method only removes whitespace from both sides of a string.

var str = "  this is sample string  "
console.log(str.trim()) // "this is sample string"

if you want to remove all white spaces you can use replace method

var str = "  this is sample string  "
console.log(str.replace(/\s/g, "")) // "thisissamplestring"

if you are thinking of validation then you should use your own validation or use other libraries for validation, these methods only return new string of specified value and does not perform any validation

Upvotes: 3

Related Questions