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.

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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)%>
Hi user1526912 I've just added a bunch more content on getting the client and server side running. Does that help at all?
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
      }
   }
  });


})

Comments

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; }

2 Comments

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
In regards to your first question take a look here for more info on validators in general: asp.net/mvc/tutorials/older-versions/models-(data)/… 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.