It is probably a good idea to create validation on part of your view model so that your model has something like the following:
[RegularExpression(@"^[\S]*$", ErrorMessage = "White space found")] public string MyField {get;set;}
Then you can do the following:
@Html.TextBoxFor(model => Model.MyField , new { }) @Html.ValidationMessageFor(model => Model.MyField)
To get work on the client side, you need to enable client-side validation and unobtrusive JS, which you can do by setting the following in the <appSettings> section of your main web.config
<add key="ClientValidationEnabled" value="true"/> <add key="UnobtrusiveJavaScriptEnabled" value="true"/>
You will also need to bring the jquery.validate.js and jquery.validate.unobtrusive.js to your page. They must be included in the scripts folder when creating a new project in MVC3.
<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
Finally, on the server side action method, you'll want something like this:
[HttpPost] public ActionResult Index(Thing myThing) { if (ModelState.IsValid) {
Relying on the client on the client side, JS is dangerous because it is theoretically possible to bypass, resulting in a data failure on the server side.
The regex above should do the test you want, but my regex skills are a little rusty.
AndyM source share