Milad Gh
Milad Gh

Reputation: 21

How to set regular expressions in cshtml razor file in asp mvc?

i want to set Regular expression in my cshtml file, please help me how i done it? i dont want use regular expression in code first.

<div class="form-group">
    @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })

    <div class="col-md-10">
       @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control", placeholder = "short name", required = "required", RegularExpressionAttribute = @"^([a-zA-Z .&'-]+)$" } })
       @Html.ValidationMessageFor(model => model.Title,"", new { @class = "text-danger" })
    </div>
</div>

Upvotes: 0

Views: 22627

Answers (1)

kblau
kblau

Reputation: 2107

This works. You need to change EditorFor to TextBoxFor. Remove the htmlAttributes, and use pattern instead of RegularExpressionAttribute:

Model:

namespace Testy20161006.Models
{
    public class Student
    {
        public int ID { get; set; }
        public String Name { get; set; }
        public String email { get; set; }
    }

}

Controller:

    [HttpPost]
    public ActionResult Index9(Student stud)
    {
        if (ModelState.IsValid)
        {
            var ap = "dh";
        }
        return View(stud);
    }

    public ActionResult Index9()
    {
        return View(new Student());
    }

View:

@model Testy20161006.Models.Student

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index9</title>
    <script src="~/Scripts/jquery-1.12.4.min.js"></script>
    <link href="~/Content/Student.css" rel="stylesheet" />
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
            @Html.TextBoxFor(model => model.Name, new { @class = "form-control", placeholder = "short name", required = "required", pattern = @"^([a-zA-Z .&'-]+)$"  })
            @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            <input type="submit" value="Submit" />
        }
    </div>
</body>
</html>

Upvotes: 8

Related Questions