开发者

DataAnnotation not popping the ErrorMessage

I am using Asp.Net 4 MVC 3.0 and Razor. I need to check the equality of two string. So I did this using Attribute for the class. I got the code from here.

This is is how I used the attribute.

    [Match("FaxNumber", "ConfirmFaxNumber", ErrorMessage = "Fax number must match")]
    public class FaxModel
    {

        [Required, StringLength(maximumLength: 10, MinimumLength = 10),
        RegularExpression(@"^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4})$",
            ErrorMessage = "Enter correct fax number.")]
        [Display(Name = "Fax number")]
        public string FaxNumber { get; set; }

        [Required, StringLength(maximumLength: 10, MinimumLength = 10),
        RegularExpression(@"^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4})$",
            ErrorMessage = "Enter correct fax number.")]
        [Display(Name = "Confirm fax number")]
        public string ConfirmFaxNumber { get; set; }

     }

And her开发者_运维技巧e is the UI implementation of the two fields.

           <div data-role="fieldcontain" class="template">
                @Html.LabelFor(expression = (m => m.FaxNumber), labelText: "Fax number:") @Html.TextBoxFor(expression: expression, htmlAttributes: new { name = "FaxNumber", value = "${FaxNumber}" })
                <blockquote>@Html.ValidationMessageFor(expression)</blockquote>
            </div>
            <div data-role="fieldcontain" class="template">
                @Html.LabelFor(expression = (m => m.ConfirmFaxNumber), labelText: "Confirm fax number:")
                @Html.TextBoxFor(expression: expression, htmlAttributes: new { name = "ConfirmFaxNumber", value = "" })
                <blockquote>@Html.ValidationMessageFor(expression)</blockquote>
            </div>

In the above piece of code expression is System.Linq.Expressions.Expression<Func<MyModels.Fax.FaxModel, object>> expression;

Now the problem is that even if the values mis-match the error message is not bubbled up. I am not getting the reason for the behavior. Help needed.

Thankyou All.


There is already such attribute built-in ([Compare]):

[Compare("ConfirmFaxNumber", ErrorMessage = "Fax number must match"]
public string FaxNumber { get; set; }

The reason this implementation is not working is because it is a class level validation attribute which doesn't add a key associated to the error, so none of the @Html.ValidationMessageFor helpers matches this error message. You will probably see it if you use the @Html.ValidationSummary(false) helper. But once again the Compare attribute is probably better suited to what you are trying to achieve.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜