Prevent user from entering white space during form

2019-02-17 18:52发布

问题:

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,

回答1:

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


回答2:

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+