0

I have This ViewModel:

   public string Address { get; set; }
   [DisplayName("Do you want Reward?")]
   public bool IsReward { get; set; }

   [Range(0,int.MaxValue,ErrorMessage="Please enter integer number")]

   [DisplayName("Reward")]
   public int Reward { get; set; }

In View IsReward property is unchecked by default, when user check Isreward and post the view, If Reward text box is empty then show an error message to the user "Please enter Reward".

How can I validate it using DataAnnotation?

Mahdi Alkhatib
  • 1,954
  • 1
  • 29
  • 43
osman Rahimi
  • 1,427
  • 1
  • 11
  • 26
  • You could write your own ValidationRule. Not really related specifically, but is an example of an implementation: http://stackoverflow.com/a/16100455/858757 Another option to make it really simple is to check it in your controller and call AddModelError("Reward", "please enter Reward"); – Silvermind Jun 02 '15 at 20:34
  • You can look at using a [foolproof](http://foolproof.codeplex.com/) `[RequiredIfTrue]` or similar validation attribute applied to the `Reward` property - `[RequiredIfTrue("IsReward", ErrorMessage="please enter Reward")] public int Reward { get; set; }` which will give client and server side validation. If you want to write your own, [this article](http://www.devtrends.co.uk/blog/the-complete-guide-to-validation-in-asp.net-mvc-3-part-2) is a good guide –  Jun 02 '15 at 22:21

1 Answers1

0

Try the following code. It will display the error message if IsReward is true and Reward textbox value is zero.

    [RewardValidation]
    public class RewardModel
    {
        public string Address { get; set; }
        [DisplayName("Do you want Reward ؟")]
        public bool IsReward { get; set; }

        [Range(0, int.MaxValue, ErrorMessage = "Please enter integer number")]

        [DisplayName("Reward")]
        public int Reward { get; set; }
    }

public class RewardValidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        RewardModel app = value as RewardModel;
        if (app.IsReward && app.Reward==0)
        {
            ErrorMessage = "please enter Reward";

            return false;
        }
        return true;
    }
}

And include the the @Html.ValidationSummary(true) in view to display the message

Golda
  • 3,823
  • 10
  • 34
  • 67
  • it shows `The Reward field is required.` instead of ` please enter Reward` . whats a problem ? – osman Rahimi Jun 03 '15 at 08:19
  • @osmanRahimi, as per the if (app.IsReward && app.Reward==0) condition if the reward is 0 (zero) then only it will show the message 'please enter Reward'. 'The Reward field is required' message triggers because the Reward data type is int. If suppose it is int? then it will never show the ' 'The Reward field is required'' message – Golda Jun 03 '15 at 08:36