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 \
.
Link to Regex on Regex101.com
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?
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][/\\]$"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With