6

I have bee using model validation in asp.net MVC website. I want to have a functionality to prevent user from entering whitespace in testbox and submit the form.

There are other validation attributes available, but i could not find any validation attribute that prevents user from entering only whitespace in the input textbox.

I could develop a custom attribute for this, but there is another method called regular expression validator which i think i could use easily to achieve this functionality. For example: We can set an attribute that has a regular expression for validating email. if User enters wrong email, immediately a message is shown that email format is wrong.

I want use the same, but i don't know the regular expresison that validates a form input field if user enters only whitespace.

Please help me with this kind of regular expression? Thanks,

3 Answers 3

13
[RegularExpression(@"[^\s]+")]
public string Data { get; set; }
0
3

Use Regex validation with this pattern:

^\S+$

This will allow only non-white-space.

(Update)

If you want users to enter whitespace but only if there are non-whitespace in there:

\S+
1
  • 1
    Hi, Thanks you all for the reply. But above two regular expression doesn't work. I want to prevent user from entering only whitespace, they can however enter whitespace along with other words, for example a full name of a person "Steve Jobs". This name consist of a whitespace, this is valid.
    – NCCSBIM071
    Jan 26, 2011 at 4:57
1

This regular expression might work

^[a-zA-Z0-9,-.@~!#$%&*<>?:;_='/()]+(\\s+[a-zA-Z0-9,-.@~!#$%&*<>?:;_='/()]+)*$
3
  • The character range ,-. is cleverly equivalent to the character range ,-.. I see what you did there.
    – tripleee
    Oct 20, 2020 at 5:54
  • Though this will still disallow leading whitespace.
    – tripleee
    Oct 20, 2020 at 5:55
  • While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.
    – Yunnosch
    Oct 20, 2020 at 6:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.