0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

@Jeyesh Tanna Yes I have that, but how is your validation message different from <span asp-validation-for="RModel.FirstName"></span>?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.