4

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.

user1526912
  • 15,818
  • 14
  • 57
  • 92

3 Answers3

4

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.

AndyM
  • 1,148
  • 1
  • 10
  • 19
  • Hi Andy thanks for your help. I added the following to my Model and controller: [RegularExpression(@"^\S+$", ErrorMessage = "White space found")] public string Url1 { get; set; }. When I go to my form I am still able to save the field with whitespaces <%= Html.ValidationMessageFor(model => Model.Url1)%> – user1526912 Jul 18 '12 at 16:32
  • Hi user1526912 I've just added a bunch more content on getting the client and server side running. Does that help at all? – AndyM Jul 18 '12 at 22:49
0

Found this code here:

$(document).ready(function(){

  jQuery.validator.addMethod("noSpace", function(value, element) { 
  return value.indexOf(" ") < 0 && value != ""; 
}, "No space please and don't leave it empty");


$("form").validate({
   rules: {
      name: {
          noSpace: true
      }
   }
  });


})
Community
  • 1
  • 1
Ecnalyr
  • 5,792
  • 5
  • 43
  • 89
0

I would recommend making the white space check as part of the model validation. A simple and reusable validation attribute for this purpose would look as follows:

public class NoWhiteSpaceAttribute : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var strValue = value as string;
        if (!string.IsNullOrEmpty(strValue))
        {
            return !strValue.Contains(" ");
        }

        return true;
    }
}

Usage example:

[NoWhiteSpace(ErrorMessage = "No spaces allowed")]
public string UserName { get; set; }
Jesse
  • 8,223
  • 6
  • 49
  • 81
  • Hi Jesse. I am kinda new to this. What's ValidationAttribute in this case. Its easy to add [NoWhiteSpace(ErrorMessage = "No spaces allowed")] to my Model properties but I am not sure how to implement the class – user1526912 Jul 18 '12 at 16:38
  • In regards to your first question take a look here for more info on validators in general: http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validation-with-the-data-annotation-validators-cs That aside, I generally add such a class to an "infrastructure" folder within my project. From there ensure that you have imported the class in your model and add the attribute. – Jesse Jul 18 '12 at 16:44