RegularExpression Validation attribute not working correctly
Solution 1
RegularExpressionAttribute
requires the full sting match:
// We are looking for an exact match, not just a search hit. This matches what
// the RegularExpressionValidator control does
return (m.Success && m.Index == 0 && m.Length == stringValue.Length);
So, you need to remove the flags (that is a typo) and use ^.*
before your pattern:
@"^.*[a-zA-Z0-9][/\\]$"
Solution 2
On Regex101 [a-zA-Z0-9][/\\]$
is used and in code @"[a-zA-Z0-9][/\\]$/img"
[RegularExpression]: Validates that the data matches the specified regular expression
So you have to invert the regex
.*[^/\\]$
See example
Note
In fact [a-zA-Z0-9][/\\]$/img
is invalid regex, since /
is not escaped in front of img
Related videos on Youtube
Jeroen
Updated on June 04, 2022Comments
-
Jeroen almost 2 years
I want to validate a property in my viewmodel to match a regular expression.
Viewmodel:
using System.ComponentModel.DataAnnotations; namespace ProjectName.ViewModels { public class ViewModel { [Required(ErrorMessage = "error message.")] [RegularExpression(@"[a-zA-Z0-9][/\\]$/img", ErrorMessage = "End with '/' or '\\' character.")] public string FilePath { get; set; } public ViewModel() { } } }
View:
@model ProjectName.ViewModels.ViewModel <form asp-action="EditPath" asp-controller="Files" id="EditFilePathForm"> <div asp-validation-summary="ModelOnly" class="text-danger"></div> <div class="col-md-5"> <div class="form-group"> <div class="col-md-12"> <label asp-for="FilePath" class="control-label"></label> </div> <div class="col-md-8"> <input asp-for="FilePath" class="form-control"/> <span asp-validation-for="FilePath" class="text-danger"></span> </div> <div class="col-md-4"> <p>@Model.FileName</p> </div> </div> </div> <div class="col-md-12 text-right"> <hr /> <button type="button" class="btn btn-default" id="cancelEditFilePathModal" data-dismiss="modal">Annuleren</button> <input type="submit" class="btn btn-primary" id="Submit" value="Opslaan"/> </div> </form>
The regular expression should check if the FilePath ends with a alphanumeric character followed by
/
or\
.On Regex101.com this seems to work fine. However when I test this in my application it seems to never match the expression and the error message keeps showing up.
What am I overlooking here?
-
Wiktor Stribiżew about 6 yearsTry
@".*[a-zA-Z0-9][/\\]$"
-
Wiktor Stribiżew about 6 yearsYes. That is the main problem, not the typo with the flags.
-