Asp – Integer validation in asp.net mvc

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 left Price as blank, Then It takes 0 as a value.

So I check it with 0.

In my Database Price cannot be null; and I am using LINQ-to-SQL class.

Now my problem is when I left Price blank it gives me two messages.e.g.

  • A value is required.
  • Price is Required.

So How do I put custom validation without showing first error message?

Relpy to comment
I am reffering book code of Professional Asp.net MVC 1.0 here.

HTML pages of Book are Here.

usefull 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;
        }
    }

Best Solution

I think you get the first message "A value is required" automatically from the framework because your Price property is a value type, which can never be null.

So when you post a blank field, the framework will usually try to assign null to this property, which is not possible in this case.

If you change the type to nullable:

public double? Price { get; set; }

That particular message should disappear. Then you could change your validation to:

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

The fact that the database field does not allow nulls should not interfere with your viewmodels.