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,
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.
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.
/^[^\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.
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.
[RegularExpression(@"[^\s]+")]
public string Data { get; set; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With