[asp.net-mvc] DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view

The DataAnnotations validator not working in asp.net mvc 4 razor view, when using the special characters in the regular expression.

Model:

[StringLength(100)]
[Display(Description = "First Name")]
[RegularExpression("^([a-zA-Z0-9 .&'-]+)$", ErrorMessage = "Invalid First Name")]
public string FirstName { get; set; }

Razor View:

@Html.TextBoxFor(model => Model.FirstName, new { })
@Html.ValidationMessageFor(model => Model.FirstName)

The unobtrusive validation is rendered in view as:

<input type="text" value="" tabindex="1" style="height:auto;" name="FirstName" maxlength="100" id="FirstName" data-val-regex-pattern="^([a-zA-Z0-9 .&amp;amp;&amp;#39;-]+)$" data-val-regex="Invalid First Name" data-val-length-max="100" data-val-length="The field FirstName must be a string with a maximum length of 100." data-val="true" class="textfield ui-input-text ui-body-d ui-corner-all ui-shadow-inset valid">

The regex pattern in the above html is not rendered as specified in the Model's RegularExpression, which results in error even when entering the valid data (Sam's).

How can i handle this?

--UPDATE--

I have updated the code as per @Rick suggestion

[StringLength(100)]
[Display(Description = "First Name")]
[RegularExpression("([a-zA-Z0-9 .&'-]+)", ErrorMessage = "Enter only alphabets and numbers of First Name")]
public string FirstName { get; set; }

View Source shows the following:

<input data-val="true" data-val-length="The field FirstName must be a string with a maximum length of 100." data-val-length-max="100" data-val-regex="Enter only alphabets and numbers of First Name" data-val-regex-pattern="([a-zA-Z0-9 .&amp;amp;&amp;#39;-]+)" id="FirstName" maxlength="100" name="FirstName" type="text" value="" />

Still i have the same issue.

This question is related to asp.net-mvc regex razor data-annotations

The answer is


What browser are you using? I entered your example and tried in both IE8 and Chrome and it validated fine when I typed in the value Sam's

 public class IndexViewModel
 {
    [Required(ErrorMessage="Required")]
    [RegularExpression("^([a-zA-Z0-9 .&'-]+)$", ErrorMessage = "Invalid First Name")]
    public string Name { get; set; }
 }

When I inspect the DOM using IE Developer toolbar and Chrome Developer mode it does not show any special characters.


This one worked for me, try this

[RegularExpression("^[a-zA-Z &\-@.]*$", ErrorMessage = "--Your Message--")]

Try escaping those characters:

[RegularExpression(@"^([a-zA-Z0-9 \.\&\'\-]+)$", ErrorMessage = "Invalid First Name")]

Try @ sign at start of expression. So you wont need to type escape characters just copy paste the regular expression in "" and put @ sign. Like so:

[RegularExpression(@"([a-zA-Z\d]+[\w\d]*|)[a-zA-Z]+[\w\d.]*", ErrorMessage = "Invalid username")]
public string Username { get; set; }

We've had similar issue in the past (as mentioned by TweeZz). In our case we're controlling outputting of TextBoxFor by our custom htmlHelper extension method which is building MvcHtmlString, there in one step we need to add these unobtrusive validation attributes, which is done via

var attrs = htmlHelper.GetUnobtrusiveValidationAttributes(name, metadata)

after call to this method, attributes are html encoded, so we simply check if there was Regular expression validator there and if so, we html unencode this attribute and then merge them into tagBuilder (for building "input" tag)

if(attrs.ContainsKey("data-val-regex"))
    attrs["data-val-regex"] = ((string)attrs["data-val-regex"]).Replace("&amp;","&");
tagBuilder.MergeAttributes(attrs);

We only cared about & amps, that's why this literal replacement


Try this one in model class

    [Required(ErrorMessage = "Enter full name.")]
    [RegularExpression("([A-Za-z])+( [A-Za-z]+)", ErrorMessage = "Enter valid full name.")]

    public string FullName { get; set; }

Try using the ASCII code for those values:

^([a-zA-Z0-9 .\x26\x27-]+)$
  • \x26 = &
  • \x27 = '

The format is \xnn where nn is the two-digit hexadecimal character code. You could also use \unnnn to specify a four-digit hex character code for the Unicode character.


The problem is that the regex pattern is being HTML encoded twice, once when the regex is being built, and once when being rendered in your view.

For now, try wrapping your TextBoxFor in an Html.Raw, like so:

@Html.Raw(Html.TextBoxFor(model => Model.FirstName, new { }))

Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to regex

Why my regexp for hyphenated words doesn't work? grep's at sign caught as whitespace Preg_match backtrack error regex match any single character (one character only) re.sub erroring with "Expected string or bytes-like object" Only numbers. Input number in React Visual Studio Code Search and Replace with Regular Expressions Strip / trim all strings of a dataframe return string with first match Regex How to capture multiple repeated groups?

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC

Examples related to data-annotations

How to add "required" attribute to mvc razor viewmodel text input editor ASP.NET MVC: Custom Validation by DataAnnotation Entity Framework code first unique column Why can't I reference System.ComponentModel.DataAnnotations? DataAnnotations validation (Regular Expression) in asp.net mvc 4 - razor view How do I specify the columns and rows of a multiline Editor-For in ASP.MVC? Disable Required validation attribute under certain circumstances Assign format of DateTime with data annotations? displayname attribute vs display attribute Int or Number DataType for DataAnnotation validation attribute