Reputation: 17220
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.
Upvotes: 4
Views: 3788
Reputation: 1200
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.
Upvotes: 4
Reputation: 8393
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; }
Upvotes: 0
Reputation: 5802
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
}
}
});
})
Upvotes: 0