dan_vitch
dan_vitch

Reputation: 4559

Validate field with Html Helper

I have the following field:

<div class="editor-label">
    @Html.LabelFor(c => c.Title)
</div>
<div class="editor-field">
    @Html.TextBoxFor(c => c.Title)
</div>
<p>
    <input type="submit" value="Create" />
</p>

I want to make sure there is a value in the title on submit. I know you can do this by adding a required attribute on the Model, but I dont want to add required attribute to the model. Can I validate to require a value just with Html helpers?

Upvotes: 0

Views: 2631

Answers (1)

DMulligan
DMulligan

Reputation: 9073

Taken from Manually validate textbox with jQuery unobtrusive validation asp.net MVC3 you could do something with jQuery like

$('#Title').rules('add', {
     required: true,
     messages: {
        required: 'The title field is required.'
     }
});

But inserting the tags manually into your html is just adding client side validation. I think its always best to have some sort of validation on your actual view model. I don't think it's overkill to do.

public class BaseViewModel
{
    //...
}

public class ViewModel1 : BaseViewModel
{
    [Required]
    public string Title { get; set; }
}

public class ViewModel2 : BaseViewModel
{
    public string Title { get; set; }
}

If the view model has different rules then it is a different view model.

Upvotes: 4

Related Questions