Regex to trim white space and special characters from an input string before submission

chatsaurav19
Tera Contributor

Hi Team,

 

There is a requirement to trim white spaces and special characters from an input string before it gets submitted.

 

Ex. If user is inputting space in beginning and after the text ends and more than one space in between  then it should get trimmed.

<space><space><space><tab>TEST<space>TEST1<space><space><tab>TEST2<space><space><space>

should become

TEST<space>TEST1<space>TEST2 ( With only one space in between )

 

Moreover only these characters could be allowed : ( ) & -   (brackets, ampersand and hyphen) and no other characters

Ex. TEST - TEST1

       TEST & TEST1

       (TEST)

       

It will be great if someone could help me with the regex logic.

Regards,

Saurabh

 

 

 

 

 

10 REPLIES 10

I think you have two different concepts... do you want to clean up what the user enters or validate that they enter a valid value?

You can have a client script use the logic above to clean up the input, then the validation can determine if what is left is acceptable. The regex to validate the input would be different.

Hi @John ,

 

So it's like the moment the user finishes typing his input, the regex would first remove the extra spaces if any then if there are any special characters ( other than those mentioned ) and pop a message stating "Special Characters are not allowed" and blank the field.

 

Regards,

Saurabh

So that would be a cleanup action performed by a script, such as an onchange or onsubmit client script. My understanding is that the validation regex does not take action, it simply says "yes" or "no" if the user has entered a valid value.

 

To simply check the input for invalid characters, you can try this:

^\s+|\s+$|[^\w\(\)\-\&| ]|\s{2,}

This will match on any leading, trailing, or multiple spaces as well as any characters that are not what you listed.

Hi @John

 

I achieved the leading, trailing and intext spaces with the below logic but for the regex one for special characters ( other than (), & and - ) it's not working

 

var first = g_form.getValue('service_name_l3');
g_form.setValue('service_name_l3', first.trim());

 

var str = newValue.toUpperCase();
if (str != newValue)
g_form.setValue("service_name_l3", str);

 

var str1 = str.replace(/\s\s+/g, ' ');
g_form.setValue('service_name_l3', str1);

 

//Not working

[^\w\d &\-\(\)\.]
[^\w\(\)\-\&| ]|\s{2,}

 

Regards,

Saurabh

how are you using the regex patterns for the special characters?