MARS
MARS

Reputation: 587

How to properly validate a form in asp.net MVC with ViewModel?

I have been following the documentation here and here, but the validation attributes don't seem to work. I have this in my RModel:

[RegularExpression(@"^[A-Z]+[a-zA-Z'\s]*$")]
[Required]
[StringLength(10)]
public string FirstName { get; set; }

[Required]
[EmailAddress]
public string Email { get; set; }

And this is in my view:

@using (Html.BeginForm("Index", "RHome", FormMethod.Post))
{
    <div class="field form-group col-sm-4">
        <input type="text" id="FirstName" placeholder=" ">
        <label for="FirstName">First Name</label>
        <span asp-validation-for="RModel.FirstName"></span>
    </div>

    <div class="field form-group col-sm-8">
        <input id="Email" placeholder=" ">
        <label for="Email">Email</label>
        <span asp-validation-for="RModel.Email"></span>
    </div>
    . . .
}

I am using a ViewModel to load in multiple models. The other models are very similar to RModel. I don't know if that will effect anything, but I think it might.

public class ViewModelR
{
    public RModel RModel { get; set; }
    public KnowledgeModel KnowledgeModel { get; set; }
}

I just want to have server and client side validation to prevent injection and incorrect inputs and stuff. How to I do this?

UPDATE: I added to my view and now when I click submit without filling either input, I seem to be getting a message that implies [required] is working.

The Email: field is required.
The First Name: field is required.

That's great, but I need to get all the other validation working so I can prevent bad values?

Upvotes: 0

Views: 81

Answers (1)

Jayesh Tanna
Jayesh Tanna

Reputation: 418

I would suggest you to use Validation message scafolding with every input html element you have in your view.

@Html.ValidationMessageFor(model => model.RHome.FirstName, "", new { @class = "text-danger" })

I hope, you have already added at least below js in your view.

jquery.validate.unobtrusive.js

Upvotes: 1

Related Questions