Home > OS >  Regex expression with white space not allow at first and allow in middle
Regex expression with white space not allow at first and allow in middle

Time:02-01

I need to write a regex which will not allow space in text box but it will allow space in middle and it will allow only alphanumeric characters. please help. I have been checking for this everywhere and tried a lot, does not work. Thanks.

CodePudding user response:

Try to use trim() it remove space from start and end only and later on apply rest reqex ^[a-zA-Z0-9\.\s]*$ for other condition like alphanumeric with space

case 1: user has typed only space

let txt=" "
let result=txt.trim();
if(!(result.length>0))
{
console.log("only space or empty input")
//perform operation you want when only space or empty value is there
}

case 2: user has typed name with space in between

let txt="hari kiran"
let result=txt.trim();
if(!(result.length>0))
{
console.log("only space or empty input")
}else
{
console.log("correct input procced furtur")
//now check alpha numeric with space
 if(result.match(/^[a-zA-Z0-9\.\s]*$/))
 {
   console.log("input with alphanumeric and space in between")
  }
}

CodePudding user response:

You may try the following pattern:

^[A-Za-z0-9] (?:[A-Za-z0-9 ]*[A-Za-z0-9] )?$

Demo

  •  Tags:  
  • Related