How to check spaces with jquery / ajax in MVC view

I have an MVC view that includes a form and now I need to check the data entered in certain text fields. I just need to make sure there are no spaces. Can anyone give me an example of validating a form using a jquery / ajax script in my opinion.

+4
source share
3 answers

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) { //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 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.

+4
source

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 } } }); }) 
0
source

I would recommend doing a space check as part of the model check. A simple and reusable validation attribute for this purpose would look like this:

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

All Articles