Validation for textbox in MVC3

2019-05-20 00:06发布

问题:

I need your help. I am working with MVC3-Razor application. I need to validate a textbox on View (.cshtml file) in such a way that, the starting 2 characters must be "PR" and 4th character must be "2". This is the requirement. How would i achieve this functionality? Any suggestions, it would be great help. Thanks for your precious time.

回答1:

Model

public class RegisterModel
{
      public int ID { get; set; }

      [RegularExpression(@"^PR[a-zA-Z0-9]2([a-zA-Z0-9]*)$", ErrorMessage = "Please enter valid Name.")]
      [Required(ErrorMessage = "Name is required.")]
      public string Name { get; set; }
}

View

@using (Html.BeginForm("DYmanicControllerPage", "Test", FormMethod.Post, new { id = "FrmIndex" }))
{ 
      <div>
          @Html.LabelFor(m => m.Name)
          @Html.TextBoxFor(m => m.Name)
          @Html.ValidationMessageFor(m => m.Name)
      </div>
}