简体   繁体   English

无法让Regex在MVC 4.0 C中为多行文本框工作#

[英]Trouble getting Regex working for multiline textbox in MVC 4.0 C#

Here is my model 这是我的模特

    [Required(ErrorMessage = "At least one 10 digit number is required.")]
    [DataType(DataType.MultilineText)]
    [RegularExpression(@"^\d{10}$", ErrorMessage = "Please enter a valid 10 digit number.")]
    public string TenDigitNumbers
    {
        get;
        set;
    }

Here is my view 这是我的看法

        @Html.TextAreaFor(model => Model.TenDigitNumbers, new { @class = "MyModel", @cols = 11, @rows = 5 })
        @Html.ValidationMessageFor(model => Model.TenDigitNumbers)<br />

This regex works for one ten digit number entered into the textbox. 此正则表达式适用于输入文本框的十位数字。 However it fails for more than one ten digit number entered into the textbox. 但是,在文本框中输入的数字超过十位数就会失败。 I have read that the regex needs multiline turned on. 我已经读过正则表达式需要打开多行。 I have done that by defining the datatype in the model above. 我通过在上面的模型中定义数据类型来做到这一点。 So I'm not sure what I am doing wrong. 所以我不确定我做错了什么。

The RegularExpressionAttribute doesn't support the MultiLine property.. you'll have to roll your own. RegularExpressionAttribute不支持MultiLine属性..你必须自己动手。

This question has already been asked on SO.. not to take away from the original author's code.. here is an example: https://stackoverflow.com/a/9689880/1517578 这个问题已经在SO上被问过了......不要带走原作者的代码..这里有一个例子: https//stackoverflow.com/a/9689880/1517578

With 10 digit numbers, do you mean something like this: 有10位数字,你的意思是这样的:

 1234567890 1234567890 1234567890 1234567890

In that case, you need an expression that understands that, something like: ^\\d{10}( \\d{10})*$ 在这种情况下,您需要一个能够理解的表达式,例如: ^\\d{10}( \\d{10})*$

Of if you're using a multiline textbox, something like: ^\\d{10}(\\r?\\n\\d{10})*$ 如果您使用多行文本框,例如: ^\\d{10}(\\r?\\n\\d{10})*$

This is how you would do it with Regex, basically not relying on multiline flag or attribute, instead you explicitly define the regex to allow new lines but the same pattern needs to follow 这就是你如何使用Regex,基本上不依赖于多行标志或属性,而是明确定义正则表达式以允许新行,但需要遵循相同的模式

    [RegularExpression(@"^\d{10}(\r?\n\d{10})*$", ErrorMessage = "Please enter a valid 10 digit number.")]
    public string TenDigitNumbers
    {
        get;
        set;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM