0

I need to add a validation control in ASP MVC for a textbox. I used the @Html.ValidationMessage helper.

There is one textbox and I want to show the error If the value is not entered in that field.

I used the following code.

@Html.TextBox("txtStudentNumber", "4234234");
@Html.ValidationMessage("txtStudentNumber", "Please enter the student number", new { @class = "text-danger" })

The above message is always shown irrespective if the textbox has a value or not.

I need to validate if the student textbox is empty and also when the save button is clicked.

Nikunj
  • 195
  • 10
user1339913
  • 1,017
  • 3
  • 15
  • 36
  • Possible duplicate of [Validation errors are always displayed](https://stackoverflow.com/questions/33960827/validation-errors-are-always-displayed) – Sahil Sharma Jan 09 '19 at 13:09

1 Answers1

0

First of all, you have to use strongly types controls. i.e you should use TextBoxFor instead of TextBox and use ValidationMessageFor instead of ValidationMessage.

and then you have to bind the textbox with model. Try this :

Step 1: Create one model class "ClsStudent"

public class ClsStudent{public int studentNo {get;set;}}

Step 2: Bind the model student number in the view : @model ClsStudent

@Html.TextBoxFor(m => m.studentNo) @Html.ValidationMessageFor(m => m.studentNo, null, new { @class = "error" })

Validation on Submit Button : Submit

Shashi
  • 91
  • 1
  • 1
  • 6