skip to Main Content

I am working small application with basic CRUD operation and I have Product Model.
In this model I have something like

public class Product  
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public int amountAvailable { get; set; }
        public double cost { get; set; }

        [ForeignKey(nameof(User))]
        public int UserId { get; set; }
        public User Users { get; set; }
        
    }

Right now, I need some shortcut or some hack how to make cost (cost of the product), but it should be a multiple of 5, meaning the price can be 5,10,15,20,25,30… etc.
Is there anything which I can force user to put price something like thiss?
I try with [DataAnnotation] and using Range but I think this will not work.

3

Answers


  1. You can make cost variable as a prop and round there any given value by user till it is valid.

    Login or Signup to reply.
  2. Try:

    public class MultipleOf5Attribute : ValidationAttribute
    {
        public override bool IsValid(object value)
        {
            return ((int)value) % 5 == 0;
        }
    }
    

    use the decimal instead of the int

    Login or Signup to reply.
  3. You can use a JS at the end of your view which is probably better as you will have a front end validation rather than posting the form before checking if it’s wrong (sorry I’m using my phone to type the suggested answer so may not be formatted properly) but something like this:

             <script>
                           document.getElementById("Submit_btn_id").addEventListener('click',function ()
                       {
    
                        //get the value entered in the input field 
                         var userEnterANumber = document.getElementById('input_id').value
    
    
                           if (userEnterANumber % 5 == 0)
                          {
                         console.write('This is a multiple of 5')
                             //turn off the required attribute from the input field 
                            document.getElementById("input_id").required = false;
                            }
       
                            else 
                            {
                              console.write('Not a multiple of 5')
                              //set the required attribute on the input field 
                            document.getElementById("input_id").required = true;
                              }
                            });
                    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search