用于控制的MVC3文本框的文本框验证 [英] Textbox validation for MVC3 textboxfor control

查看:97
本文介绍了用于控制的MVC3文本框的文本框验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友们,

我正在从事MVC3项目.我想用两个条件验证一个文本框.

1)无需允许将空字符串插入数据库.
2)不需要接受特殊字符和数字.

特定部分页面的剃刀视图是:

Hi friends,

I''m working on MVC3 project. I want to validate one textbox with two conditions.

1) Need not allow null strings to get insert into database.
2) Need not accept special characters and numbers.

Razor view for particular partial page is:

@Html.TextBoxFor(m=>m.shortDescription)


模型类


Model class is

[Required(ErrorMessage = "Required")]
        [RegularExpression(@"^[a-zA-Z]+", ErrorMessage = "Use letters only please")]
        public string roleShortDescription { get; set; }


如何实施验证?
我可以使用jQuery吗?如果可以,怎么办?
请帮帮我!!!!

问候,
R.K.PRABAKAR


How can i implement the validation?
Can i use jquery? if so, how?
Please help me !!!!

With regards,
R.K.PRABAKAR

推荐答案

您需要在服务器上进行验证,任何客户端验证都很容易被破解.您可以在您的文本框中添加一个按键事件处理程序,并在用户键入时进行验证.在读取视图模型中的值时可以检查空字符串,只需使用??即可.用string.Empty替换null.

我要说的是Razor与它无关,但是我意识到那是不对的. HTML中的文本框如下所示:

< input type ="text" ...

然后一个按键事件将是这样的:

< input type ="text" onkeypress ="OnKeyPress(this)" ...

其中OnKeyPress是javascript方法,这意味着您的输入控件已传递给它.

[ ^ ]是有关js事件的一些文档.

在这里 [
You need to validate on the server, any client side validation is easily hacked. You can add a keypress event handler to your textbox and validate as users type. The check for null strings you can do when you read the values in your viewmodel, just use ?? to replace null with string.Empty.

I was going to say that Razor has nothing to do with it, but I realised that is not true. A textbox in HTML is like this:

<input type="text"...

and then a key press event would be like this:

<input type="text" onkeypress="OnKeyPress(this)"...

where OnKeyPress is a javascript method, and this means your input control is passed in to it.

This[^] is some documentation on js events.

Here[^] is an example to allow only numeric key presses.

The problem you have is, when you use TextBoxFor, how do you get that code in there ? The answer is, an override of TextBoxFor that takes an anonymous collection of name value pairs which are then added as attributes to the element:

@Html.TextBoxFor(m => m.Product, new { @class = "normalcell", size = "38", maxlength = "255" })



这来自我自己的代码,它将发出以下信息:

< input type ="text" id ="Product" class ="normalcell" size ="38" maxlength ="255"/>

因此,您可以这样做:




This is from my own code, and it will emit this:

<input type="text" id="Product" class="normalcell" size="38" maxlength="255"/>

so, you would do this:


@Html.TextBoxFor(m=>m.shortDescription, new { @onkeypress="MyValidationMethod" })


这篇关于用于控制的MVC3文本框的文本框验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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