How to validate textbox in MVC3 that must contain

2019-09-09 05:27发布

问题:

i am very much new to MVC3 and working with MVC3 razor application. I need to validate a textbox on View in such a way that, the textbox will accept only those strings which are starting with characters "PR" and 4th character of that string must be "2". It would be great if anybody helps me. Thanks in advance

回答1:

Well you need regex. I'm not exactly sure what the regex would be and what your string contains. But if you need to have 2 matches in there, you could split it and use 2 textboxes and join the values on post.

ViewModel:

public class MyViewModel 
{
    [RegularExpression("^PR[A-Za-z0-9]", ErrorMessage= "Invalid Text1")]
    public string MyText1 { get; set; }

    [RegularExpression("^2[A-Za-z0-9]", ErrorMessage= "Invalid Text2")]
    public string MyText2 { get; set; }
}

Warning, this regex may be faulty. I invite others to edit/post comments and i can update it with correct regex

View:

@model MyProject.Models.MyViewModel

@using (Html.BeginForm())
{

     @Html.TextBoxFor(m => m.MyText1)
     @Html.TextBoxFor(m => m.MyText2)

     <button type="submit">Submit</button>

}

Hope this helps



回答2:

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>
}