Home > Software design >  How to Allow Only specific Decimal values in a text box in ASP.NET MVC
How to Allow Only specific Decimal values in a text box in ASP.NET MVC

Time:08-24

I have a textbox called UnitValue which should accept only 3 decimal values, that is 0.1, 0.2, 0.3.

I am using data annotations on "UnitValue" property in my model class to verify the values for integers as below for Eg,

[RegularExpression("[0]{1}|[1]{1}",ErrorMessage="error")
Public int UnitHead {get;set;}

Public decimal UnitValue{get;set}
I wanted the similar way to happen for decimal property also. requesting your help on getting this validation done.

Thanks in advance

CodePudding user response:

You can create your own custom validation something like this

    public class CustomDecimalValues:ValidationAttribute  
    {  
        public override bool IsValid(object value)  
        {  
            // write your own logic for validation
            var decPlaces = (int)(((decimal)value% 1) * 100); 
            return (0.1<= decPlaces &&  decPlaces <= 0.3);  
        }  
    }  

then use in model like this

[CustomDecimalValues(ErrorMessage = "Allowed decimal values are 0.1,0.2 and 0.3")]  
Public decimal UnitValue{get;set} 

Please find the complete example using link Custom Validation

  • Related