简体   繁体   中英

How to Allow Only specific Decimal values in a text box in ASP.NET MVC

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM