如何验证使用jQuery / AJAX的空格在MVC视图 [英] How to validate whitespaces using jquery/ajax in an MVC view

查看:79
本文介绍了如何验证使用jQuery / AJAX的空格在MVC视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有包括形式的MVC视图,现在需要验证特定文本字段中输入的数据。我只是需要确保没有空格。有人可以给我使用jQuery / AJAX脚本,在我看来,表单验证的例子。

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.

推荐答案

这可能是一个好主意,建立验证到您的视图模型的一部分​​,所以你有这样的事情在你的模型如下:

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)

要获得客户端的工作,你必须启用客户端验证和不显眼JS,你可以通过设置&LT下面做;的appSettings>将部分的主的web.config

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"/>

您还需要带上 jquery.validate.js jquery.validate.unobtrusive.js 文件到您的网页。他们应该无论在脚本文件夹时,您创建MVC3一个新的项目捆绑在一起。

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

在客户端的JS wholy依托是危险的,因为它在理论上是可能绕过导致损坏的数据获取到服务器端。

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.

这篇关于如何验证使用jQuery / AJAX的空格在MVC视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆