2

I have an input address field with a custom form validation. I would like to disable only the leading space when user starts typing some text

Vue JS Form

I have checked this post however, this approach disables white space completely

I have also tried using .trim() method along with .replace(/(^\s*)|(\s*$)/gi, "") still didn't work

Here is how it looks when I have leading whitespace.

Having leading whitespace doesn't let form validation error message to be displayed

Please Note my component is a child component and I am looking for a solution which can be implemented within my component.

enter image description here

Need some help

Tried this approach but it disables all spaces by default

<input 
  v-on:keydown='key'
  class="input search-city"
  type="text"
  placeholder="Street address or zip code"
  v-model="search_string"                         
/>

<script>
 methods: {
   key: function(event){
      if(event.keyCode === 32){
        event.preventDefault();
      }
    }
  }
</script>
2
  • Do you want to disable white space in the input, or just trim the white space from the generated v-model value? Commented Dec 4, 2019 at 3:05
  • need to disable in the input so that user's first input can be a character. Commented Dec 4, 2019 at 3:07

3 Answers 3

3

Both the .trim() method and .replace(/(^\s*)|(\s*$)/gi, "") will remove leading and trailing space from your string.

To remove just the leading white-space use .replace(/^\s*/, "")

RegEx Explanation:

  • ^\s* is any repeated (*) white space (\s) following the start (^) of the input.
  • \s*$ is any repeated (*) white space (\s) preceeding the end ($) of the input.
  • (^\s*)|(\s*$) is either of the above (| = OR)
  • the /g option is "global", so it will replace multiple occurrences of the same match (not required in this case, since we are already using \s* to match repeated consecutive whitespace characters)
  • the /i option means case-insensitive match, which is not required in this case.

Alternatively, try:

<input v-model="search_string" @keydown.space="preventLeadingSpace"/>
  methods: {
    preventLeadingSpace(e) {
      // only prevent the keypress if the value is blank
      if (!e.target.value) e.preventDefault();
      // otherwise, if the leading character is a space, remove all leading white-space
      else if (e.target.value[0]==' ') e.target.value = e.target.value.replace(/^\s*/, "");
    },
  }
Sign up to request clarification or add additional context in comments.

6 Comments

an alternative way didn't work. Error: Cannot read property 'replace' of null My initial method also had the same error
Can you show your exact code - I don't understand how e.target can be null in this case. Anyway, you could try else if (e.target.value && e.target.value[0]==' ')...
In your component definition, are you initlizing search_string as null or ""? If null try changing the initial value to "".
I am about to try it tomorrow and will let you know... yes it was set to 'null'
it worked as I changed search_string from null to ""
|
3

need to disable in the input so that user's first input can be a character.

You can use custom directives.

Put this code in the file where you initiate vue

Vue.directive('disable-leading-space', { // you can rename it to your liking
    update (el) {
        // using regex to only remove spaces at the beginning
        el.value = el.value.replace(/^\s+/g, ""); // or you can use your own preferred way to remove leading spaces
        el.dispatchEvent(new Event('input'))
    }
})

and then you can use the directive like this

<input v-disable-leading-space v-model="myText">

Using directive like this makes the code to be reusable in all your vue components.

5 Comments

since I have a component I can't use Vue.directive directly ...
@DurdonaAbdusamikovna I mean put it in where you initiate vue, not in component. The file in where you import Vue from 'vue' and initiate new Vue({ router, store, render: h => h(App) }).$mount('#app'). Put it after import and before new Vue
I can't put it there since my component is a child component ... need a solution within my component
@DurdonaAbdusamikovna No problem, the directives you register will be available globally anyway. Or maybe I misunderstand your structure, put your child component, and how you call it in the question.
just edited my question. Thanks for your efforts anyway
2

Another much simpler solution:

<input v-model.trim="search_string" .....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.