Search code examples
c#regexdata-annotations

what can be the regex for string that does not allow to enter only blank space or any other special character?


I am trying to validate Address field which is marked as Required in my project. But it allows user to enter only blank space and special character in field and proceed further which ideally should not happen.

Below are the regex that I have tried:

^[*|\":<>[\\]{}`\\()';@&$]*$

^[0-9]+\s+([a-zA-Z]+|[a-zA-Z]+\s[a-zA-Z]+)$

Please suggest what am I doing wrong here.

Edit: Below image shows that it doesn't accepts valid address but allows complete blank spaces

enter image description here

I want address field to accept alphanumeric field but should not allow complete blank spaces and only special characters.

for example:

Valid:

RBI Square
123 Mount road

Invalid :

"Complete blank spaces"
.!@#$%^&*()_+|}{[]":';><//., (Completely special characters)

Solution

  • You could try this pattern ^(?=.*[a-zA-Z0-9]).+.

    With positive lookahead you check if characters, starting from the beginning of a line (anchor ^) contain at least one upper or lower case letter or digit. If that condition is satisfied, match whole line with .+ after lookahead.

    Demo.

    I recommend this for further reading.

    UPDATE

    This pattern will match additioonaly blank spaces ^(?=(.*[a-zA-Z0-9]| +)).+.

    Update demo.