OleHansen
OleHansen

Reputation: 111

Add required to LabelFor

I'm having the following code:

@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })

And I'm looking for a way to add the html attribute required to it, so a user can't submit without having the field filld. But now sure how to do? I know the easies way is to add required But don't know how, i tryed with @html "reguired" Without any luck.

EDIT: Answere = required = ""

Upvotes: 4

Views: 220

Answers (2)

Sandip Bantawa
Sandip Bantawa

Reputation: 2880

You will need this for client validation

"~/Scripts/jquery.js"
, "~/Scripts/jquery.validate.js"
,"~/Scripts/jquery.validate.unobtrusive.js"

whereas for only server side on Controller or necessary even if some disables javascript

if (ModelState.IsValid)

As above using annotation

[Required(ErrorMessage = "Title is required")]
public string Title { get;set; }

Using Fluent API

    public class ClassNameConfiguration : EntityTypeConfiguration<ClassName>
    {
        public ClassNameConfiguration()
        {
            Property(x => x.Title).IsRequired();
        }
    }

Upvotes: 0

Vadim Martynov
Vadim Martynov

Reputation: 8902

You can add RequiredAttribute to your model property:

[Required(ErrorMessage = "Title is required")]
public string Title { get;set; }

And add ValidationMessageFor to your cshtml:

@Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(m => m.Model)

Then add model validation to controller method via. It's the standard pipeline for asp.net mvc.

You also can implement your own HtmlHepler to add required attribute to your html code.

Upvotes: 2

Related Questions