Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent user from entering white space during form input in asp.net model validation?

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,

like image 274
NCCSBIM071 Avatar asked Jan 25 '11 12:01

NCCSBIM071


People also ask

How to restrict user to enter space in input field?

Solution 2Handle the KeyPress event for this textBox and put a single condition like. Here textBox1 is your textbox. This code will prevent user to enter space at begining of TextBox. Then You need to check first character of TextBox whether it's a space or not.

How to restrict space in TextBox in ASP net?

You must use a RequiredFieldValidator in conjunction with it to prevent blank entries since the RegularExpressionValidator does not prevent that on its own. Specify the name of the textbox in the ControlToValidate property.

How can you prevent someone from entering space at the beginning of a TextBox?

/^[^\t]. */ checks if the string starts with any character but a space, if you want to exclude all white spaces use /^[^\s]. */ instead. And now add the required and NoWhiteSpaceAtBeginn as class names to the fields you want to validate.

How to validate ModelState in MVC?

When MVC creates the model state for the submitted properties, it also iterates through each property in the view model and validates the property using attributes associated to it. If any errors are found, they are added to the Errors collection in the property's ModelState . Also note that ModelState.


1 Answers

[RegularExpression(@"[^\s]+")]
public string Data { get; set; }
like image 57
Darin Dimitrov Avatar answered Nov 15 '22 10:11

Darin Dimitrov