SoftwareSavant
SoftwareSavant

Reputation: 9737

Displaying jquery validation message on Label for input in MVC razor

I am attempting to get jquery validation for MVC razor up and working. I did this before in MVC2 but I need to figure out how to get this working using LabelFor(DateOfBirth => Model.DateOfBirth)...

For some reason, the message never pops up in the label. I have looked at the debugger, and I don't se it there either

<tr><td>
      @Html.LabelFor(DateOfBirth => Model.DateOfBirth)
      </td>
      <td>
      @Html.TextBoxFor(DateOfBirth => Model.DateOfBirth, new { @Value = Model.DateOfBirth })
</td></tr>

that would be the table row that contains my DateOfBirth row element...

rules:{
       DateOfBirth: {
            required: true
       }
},
messages: {
            HospitalFinNumber: 'Please Enter a valid Hospital Fin number',
            DateOfBirth: 'Please enter a valid Date Of Birth',
            AdmitDate: 'Please select an Admit Date',
            Comment: 'Why dont you stop attempting to put in more than 4000 characters?  Thanks...'
}

My message for DateOfBirth doesn't show up in the label... Am I missing something?

Upvotes: 0

Views: 846

Answers (2)

Travis J
Travis J

Reputation: 82287

Your lambda is not well formed.

@Html.LabelFor(DateOfBirth => Model.DateOfBirth)

should be

<tr><td>
  @Html.LabelFor(m => m.DateOfBirth)
  </td>
  <td>
  @Html.TextBoxFor(m=> m.DateOfBirth, new { @Value = Model.DateOfBirth })
</td></tr>

Upvotes: 0

drcoderz
drcoderz

Reputation: 341

Everything seems to be fine with the way you are using the HTML helpers and your properties. Two things to check:

-Make sure you are importing the jquery.validate libraries

-Make sure that in your model, your property DateOfBirth is decorated with the [Required] attribute, plus setting the ErrorMessage property, as follows:

    [Required(ErrorMessage="Field Required")]
    public Datetime DateOfBirth { get; set; }

Upvotes: 1

Related Questions