0

我在 ASP MVC3 中工作。我有一个输入客户联系信息的模型。该信息是必需的。当 viewstat 无效时,文本框必须有一个红色边框(这有效)en no errormessage。但是当 emailinput 无效时,错误必须在视图上可见。因此,只有电子邮件注释的错误消息必须可见,而不是必需的注释。我不知道该怎么做。

模型:

    [Required]
    public string FirstName { get; set; }
    [Required]
    public string Name { get; set; }
    [Required]
    public string Address { get; set; }
    [Required]
    public string PostalCode { get; set; }
    [Required]
    public string City { get; set; }
    [Required]
    public string Country { get; set; }
    [Required]
    public string PhoneNumber { get; set; }
    public string Fax { get; set; }
    [Required]
    [Email]
    public string Email { get; set; }

看法:

<div class="row-fluid">
    <div class="span6">
                <div data-role="fieldcontain" class="ui-hide-label">
                    <label for=@Lingo.language.Obj_Telefoon>@Lingo.language.Obj_Telefoon</label>
                    <span>@Html.TextBoxFor(m => m.PhoneNumber, new { style = "width:90%!important;", placeholder = @Lingo.language.Obj_Telefoon })</span>
                </div>               
    </div>
    <div class="span6">
        <div data-role="fieldcontain" class="ui-hide-label">
            <label for=@Lingo.language.Obj_Fax>@Lingo.language.Obj_Fax</label>
            <span>@Html.TextBoxFor(m => m.Fax, new { placeholder = @Lingo.language.Obj_Fax })</span>
        </div>  
    </div>
 </div>
 <div class="row-fluid">
    <div class="span12">
        <div data-role="fieldcontain" class="ui-hide-label">
            <label for=@Lingo.language.Obj_Email>@Lingo.language.Obj_Email</label>
            <span>@Html.TextBoxFor(m => m.Email, new { style = "width:98%!important;", placeholder = @Lingo.language.Obj_Email })</span>
            <span>@Html.ValidationMessageFor(m => m.Email)</span>
        </div>  
    </div>
 </div>
4

2 回答 2

1

写下所需的消息,如下所示:

[Required( ErrorMessage = "The first name is required" )]
public string FirstName { get; set; }
于 2012-04-11T09:38:51.037 回答
0

如果您希望它是必需的,但不想显示“必需”错误消息,您可以将消息设置为单个空格(以避免运行时错误“必须设置 ErrorMessageString 或 ErrorMessageResourceName,但不是都。”)

[Required(ErrorMessage = " ")]
[Email(ErrorMessage = "Must be a valid email address.")]
public string Email { get; set; }

如果您还没有该Email属性,您可以创建一个类文件(例如 EmailAttribute.cs),其中包含:

using System.ComponentModel.DataAnnotations;

public class EmailAttribute: RegularExpressionAttribute {
    public EmailAttribute()
      : base(@"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$") { }
  }
于 2012-04-11T09:57:41.093 回答