简体   繁体   中英

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.

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

With 10 digit numbers, do you mean something like this:

 1234567890 1234567890 1234567890 1234567890

In that case, you need an expression that understands that, something like: ^\\d{10}( \\d{10})*$

Of if you're using a multiline textbox, something like: ^\\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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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