I have created a custom Validation attribute, to check PhoneNumbers:
public class PhoneNumberIsValidAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value != null)
{
string phoneNumberRaw = (string)value;
Regex regex = new Regex(@"^\d{6,8}$");
Match match = regex.Match(phoneNumberRaw);
if (match.Success)
{
return true;
}
}
return false;
}
}
I annotate my model:
public class MyModel
{
[DisplayName("Override phone number")]
[PhoneNumberIsValid("Test")]
public string OverridePhoneNumber { get; set; }
}
And in myView:
@Html.ValidationSummary(false, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.OverridePhoneNumber)
@Html.TextBoxFor(model => model.OverridePhoneNumber, new { @class = "form-control input-text", @maxlength = GlobalConstants.MaxLengthForPhoneNumber /*, @type = "url" */})
@Html.ValidationMessageFor(model => model.OverridePhoneNumber, "", new { @class = "text-danger" })
</div>
Everything works as expected, as demonstrated in this fiddle
Here is the problem
Unfortunately I cannot demonstrate the issue on the fiddle.
If I put the input
inside _MyPartialView, and call it from MyView as shown below:
@Html.Partial("path/_MyPartialView", Model)
Then the ValidationMessage
does not show under the input
box as shown below:
This problem only happen when:
- The input is inside a PartialView
- When the error message comes from the server (client-side error messages are displayed correctly)
*I got this error with both .NET Framework 4.6.1 and 4.7.2.
` tag?
– Jackdaw Aug 28 '21 at 11:19