Home > Mobile >  how to allow input to have spaces?
how to allow input to have spaces?

Time:12-12

hey so I have a form that I add eventually to a json list, the input has to be english or numbers. I have this code below which works for me but when I submit something with two words I have an error.

// c1 = alter all english letters to check if input is in english
const english = /^[A-Za-z0-9.]*$/;
form.addEventListener("submit", (e)=>{
    // c1
    if(!english.test(seller_name.value)){
        alert("Bad input! Enter only English letters.");
        e.preventDefault();
    }else if(!english.test(seller_domain.value)){
        alert("Bad input! Enter only English letters.");
        e.preventDefault();
    }
    
});

I tried doing this but it didn't work:

// c1 = alter all english letters to check if input is in english
const english = /^[A-Za-z0-9.]*$/;
const space = " ";
const combined = english space

form.addEventListener("submit", (e)=>{
    // c1
    if(!combined.test(seller_name.value)){
        alert("Bad input! Enter only English letters.");
        e.preventDefault();
    }else if(!combined.test(seller_domain.value)){
        alert("Bad input! Enter only English letters.");
        e.preventDefault();
    }
    
});

CodePudding user response:

Just add a space to your RegEx.

^[A-Za-z0-9. ]*$

CodePudding user response:

I think you only need to add the \s to your regex definition in order to allow white spaces.

const english = /^[A-Za-z0-9.\s]*$/;

CodePudding user response:

The pattern might look like this: ([a-zA-Z] \s*)*

  • [a-zA-Z] - any a-z, A-Z character
  • 1 or more of the previous group
  • \s* 0 or more spaces
  • wrapped in ()* to allow multiple

Nice Regex cheatsheet

<form>
  <input pattern="([a-zA-Z] \s*)*" />
  <button>Submit</button>
</form>

  • Related