How to validate whitespaces using jquery/ajax in an MVC view

asp.net-mvc, c#

Solution

It's probably a good idea to build the validation into part of your view model so you would have something like the following in your model:

[RegularExpression(@"^[\S]*$", ErrorMessage = "White space found")]
public string MyField {get;set;}

You can then do the following in your view:

@Html.TextBoxFor(model => Model.MyField , new { })
@Html.ValidationMessageFor(model => Model.MyField)

To get the client side working you will have 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` files into your page. They should both be bundled in the scripts folder when you create 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 which looks a little like this:

    [HttpPost]
    public ActionResult Index(Thing myThing) {

        if (ModelState.IsValid) {
            //Do some work in here because we're all good
            return RedirectToAction("MyOtherAction");
        }

        //Oops the validation failed so drop back to the view we came from
        return View();
    }

Relying wholy on client side JS is dangerous as it is theoretically possible to bypass resulting in broken data getting to the server side.

The regex above should do the validation you want but my regex skills are a little rusty.

Problem

I have a MVC view that includes a form and now need to validate data entered in specific text fields. I just need to ensure that there are no white spaces . Can someone give me an example of form validation using jquery/ajax script in my view.

Original source

Related problems