4

I have a requirement where there is a customet name text box and the user able to input customer name to search customer. And the condition is user can add do wild card search putting * either infront or after the customer name. And the customer name should be minimum three characters long. I am using Regex to validate the user entry. Now in case the input is like "*aaa*" .. I am validate this type of input using the following regex :

[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}

The code is like below:

    var str = "*aaa*";
    var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
    var res = patt.test(str);  
    alert(res);

    var str = "*aaa***";
    var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
    var res = patt.test(str);  
    alert(res);

    var str = "*aaa*$$$$";
    var patt = new RegExp("[*]{1}([a-z]|[A-Z]|[0-9]){3,}[*]{1}");
    var res = patt.test(str);  
    alert(res);

Now for the input "*aaa*" res is coming true. But for this type of inputs also "*aaa**", "*aaa*$" its comimg true. And this expected as these expressions also contains the part( *aaa*) which satisfies the regex.But these inputs("*aaa**", *aaa*$** etc. ) are wrong.

Please let me know where I am doing wrong ? is there any issue with the regex or the way checking is wrong ?

0

2 Answers 2

2
^(?:[*]([a-z]|[A-Z]|[0-9]){3,}[*])$

Use anchors ^$ to disable partial matching.See demo.

https://regex101.com/r/tS1hW2/17

Sign up to request clarification or add additional context in comments.

3 Comments

Could you please explain me what changes u did... ^$ these u used so that the whole string is matched againts the regex. But why u have used ?:
@Sambuddha when you dont use ^$ regex will make partial matches .from *aaa** it will match *aaa* and pass.When you add anchors it wont unless complete string is matched
I guess ^[*][a-zA-Z0-9]{3,}[*]$ is a much better way to write this regex. With i option, it is even shorter: /^[*][a-z0-9]{3,}[*]$/i.
1

The string *aaa*$$$ contains a segment of *aaa*, so it will yield true; to match against the whole string you need to add anchors on both sides. The $ and ^ anchors assert the start and end of the subject respectively.

Also, you can simply the expression greatly by using a character class trick. The \w is comprised of [0-9a-zA-Z_], and we only don't want the underscore, so we can use a negative character class with the opposite of \w (which is \W) and an underscore; I agree, it takes some mental power ;-)

var str = "*aaa*$";
    var patt = /^\*[^\W_]{3,}\*$/;
    var res = patt.test(str);  
    alert(res); // false

Alternatively, you can merge all your character classes together into one like so:

[A-Za-z0-9]

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.