0

I don't want opinions. I want answers to this question below. I know within my Model classes, I can include Data Annotations to validate my forms:

public class Movie
{
    public int Id { get; set; }
    public string Title { get; set; }

    [Display(Name = "Release Date")]
    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode =true, DataFormatString = "{0:yyy-MM-dd}")]
    public DateTime ReleaseDate { get; set; }

    public string Genre { get; set; }

    [DataType(DataType.Currency)]
    public decimal Price { get; set; }

}

However, there are already JavaScript libraries that validate the default behaviors (i.e. @Html.ValidationMessageFor()):

<div class="form-group">
    @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })

And my question would be... Is it best practice to validate in the models only or within the views itself?? What is more safe in terms of maintaining security?

Please let me know if this is wrong question to ask and I will remove it quickly.

Thank you

nerdyhyun
  • 33
  • 7

1 Answers1

4

Html.ValidationMessageFor will generate the required HTML depending on the attributes in your model. So if you have a model with a property like this:

public string Name { get; set; }

Then nothing will be generated. However, if you have this:

[Required]
public string Name { get; set; }

Then the HTML generated will have info this field is required. Consequently, you will get JavaScript support to ensure the user fills the field before submitting the form. In other words, just because you have Html.ValidationMessageFor does not mean you get validation. You still need the data annotations on your model to help the view engine generate the HTML attributes such as required="required" and so on.

Validation on the client, using JavaScript, is for convenience and better user experience. However, you should always validate on the server even if you have validated the data on the client. DO NOT trust the client. Plus in some cases JavaScript may be disabled so your JavaScript validation may never get triggered, thus, another reason why you should always perform validation on the server side.

CodingYoshi
  • 25,467
  • 4
  • 62
  • 64