Judo
Judo

Reputation: 5247

Simple Validation for a Single Text Box in ASP.NET MVC

I have added a text box to a simple form in ASP.NET MVC and I want a client-side 'required' validation for this.

I know I can do this using a strongly typed model view but I would like to do it manually in this case. Is there a simple way to perform this?

I tried setting the Model/property name of the Html.ValidationMessage helper to the input name but this didnt work:

@Html.TextBox("emailStr" )
@Html.ValidationMessage("emailStr","* Required")

Upvotes: 2

Views: 5302

Answers (2)

PeteGO
PeteGO

Reputation: 5781

Not sure why you would want to do it manually - but I don't think you can use @Html.ValidationMessage unless you use a TextBoxFor. You can't use the TextBoxFor unless you have a model to work with inside the view.

You could write some javascript/jquery to find the textbox and make sure it's not empty, and if it is, unhide an element with the validation message in it.

Upvotes: 0

archil
archil

Reputation: 39491

Assuming you use default jQuery validation plugin, you can use Rules.Add method on client side for this

$("#emailStr").rules("add", {
 required: true,
 messages: {
   required: "* Required",
 }
});

Also, do not forget to include jquery.validate.min.js

Upvotes: 2

Related Questions