I
I
int02h2011-11-18 14:26:55
ASP.NET
int02h, 2011-11-18 14:26:55

[SOLVED] Form data validation in ASP.NET MVC 3?

Good afternoon.
I have an ASP.NET MVC 3 application that has user input validation. It is necessary to make sure that the value in a particular form field is strictly greater than zero. To do this, I create my GreaterNullAttribute attribute, since the Range attribute is not suitable:

<br>
public class GreaterNullAttribute : ValidationAttribute<br>
{<br>
  protected override ValidationResult IsValid(object value, ValidationContext validationContext)<br>
  {<br>
    if (IsValid(value))<br>
      return ValidationResult.Success;<br>
    return new ValidationResult("Error!!!!!");<br>
  }<br><br>
  public override bool IsValid(object value)<br>
  {<br>
    if (value is Single)<br>
    {<br>
      return (Single) value > 0;<br>
    }<br>
    return false;<br>
  }<br>
}<br>

Then I create the model:
<br>
public class MyModel<br>
{<br>
  [Required]<br>
  [DisplayName("Вещественное число")]<br>
  [GreaterNull]<br>
  public Single Number { get; set; }<br>
}<br>

And I create a view:
<br>
@model MyProject.Models.MyModel<br><br>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script><br>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script><br><br>
@using (Html.BeginForm()) {<br>
    @Html.ValidationSummary(true)<br>
    <fieldset><br>
        <legend>Model</legend><br><br>
        <div class="editor-label"><br>
            @Html.LabelFor(model => model.Number)<br>
        </div><br>
        <div class="editor-field"><br>
            @Html.EditorFor(model => model.Number)<br>
            @Html.ValidationMessageFor(model => model.Number)<br>
        </div><br>
        <p><br>
            <input type="submit" value="Submit" /><br>
        </p><br>
    </fieldset><br>
}<br>

After that, I enter negative data in the number field, click the Submit button and get NO validation errors. The form is successful.
Where am I wrong? Tell me please. Thanks in advance for your reply.
PS: Why does Habr say that you need to put habracut in the question?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anatoly, 2011-11-18
@taliban

Maybe I'm wrong, but isn't your code server-side validation? Like it or not, C# runs on the server.
PS A: Habr has been buggy lately.

I
intation, 2011-11-18
@intation

Excuse me of course, but the 21st century is in the yard, HTML5 in the browser ... on the client side, incorrect data simply will not pass = less dancing with a tambourine ...

I
int02h, 2011-11-18
@int02h

Hm. I figured it out myself. If anyone needs help, write.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question