Integer validation in asp.net mvc

I am using server side validation like

 public IEnumerable<RuleViolation> GetRuleViolations()
    {
        if (String.IsNullOrEmpty(Name))
            yield return new RuleViolation("Name is Required", "Name");
        if (Price == 0)
            yield return new RuleViolation("Price is Required", "Price");
        yield break;
    }

      

When I leave the price as blank, then it takes the value 0 as its value.

So, I check it with 0.

In my database, the price cannot be zero; and I am using LINQ to SQL class.

Now my problem is that when I left Price blank it gave me two messages. For instance,

  • A value is required.
  • Price is required.

So how do I add a custom validation without showing the first error message?

Undo comment I am posting the code of the Professional Asp.net MVC 1.0 book here .

Book HTML Pages Here .

helpful page .

public class RuleViolation
    {
        public string ErrorMessage { get; private set; }
        public string PropertyName { get; private set; }

        public RuleViolation(string errorMessage)
        {
            ErrorMessage = errorMessage;
        }

        public RuleViolation(string errorMessage, string propertyName)
        {
            ErrorMessage= errorMessage;
            PropertyName = propertyName;
        }
    }

      

+1


a source to share


3 answers


I think you will get the first "Value Required" message automatically from the framework because your property Price

is a value type that can never be null.

So when you post an empty field, the environment usually tries to assign to null

that property, which is not possible in this case.

If you change the type to nullable:

public double? Price { get; set; }

      



This particular message should disappear. Then you can change your check to:

    if (Price == null)
        yield return new RuleViolation("Price is required", "Price");

      

The fact that the database field is non-nullable shouldn't interfere with your views.

+5


a source


To do what Thomas Eyde wrote above (without using code) you can ...

  • Open the appropriate .dbml file
  • Click the "Price" property
  • In the Visual Studio Properties window change the Nullable value from False to True
  • Save the file!


Now you can go to your class and add an if statement and VS shouldn't complain.

+2


a source


This is because the default binding error adds this error. You can write your own binder for this particular object and work directly with the collection of forms to have more control over validation.

+1


a source







All Articles