2

I need to do validation on text box such that it can only accept integers from 3 to 1440 or "Default" word. range validator control does not work in this case and probably have to use custom validator control and jquery I am assuming.anyone with a solution similar to this?

NoStressDeveloper
  • 491
  • 3
  • 9
  • 26
  • Because the "default" value there is no ready implementation for it, but you can write your on custom validation attribute http://www.c-sharpcorner.com/UploadFile/rahul4_saxena/mvc-4-custom-validation-data-annotation-attribute/ – Lucas Roselli Sep 23 '15 at 20:29

3 Answers3

3

You can follow below example for your requirement:

<input type="text" id="txtbox" runat="server" onchange="javascript:return validateRange();" />

Javascript code:

<script type="text/javascript">
         function validateRange() {
            var txtVal = document.getElementById("<%=txtbox.ClientID%>").value;
            if ((txtVal >= 3 && txtVal <= 1440) ||(txtVal == "Default")) {
                return true;
            }
            else
                alert('Please enter a number between 3-1400 or Default');//Also you can set this message to an existing label
            return false;
        }

</script>
Ruchi
  • 1,238
  • 11
  • 32
0

Create a custom validation attribute

  public class CustomRangeValidator : ValidationAttribute  
    {  
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)  
        {  
            if (value != null)  
            {  
                string inputValue= value.ToString();  

                if (some if statement)  
                {  
                    return ValidationResult.Success;  
                }  
                else  
                {  
                    return new ValidationResult("Please Enter a Valid Email.");  
                }  
            }  
            else  
            {  
                return new ValidationResult("" + validationContext.DisplayName + " is required");  
            }  
        }  

then in your class:

 [CustomRangeValidator]  
    public string Email { get; set; }  
Ruchi
  • 1,238
  • 11
  • 32
Lucas Roselli
  • 2,810
  • 1
  • 15
  • 18
0

My question needed a validation for integers and all cases of default too. so i used following in addition to @ruchi rahul answer.

 if ((txtVal >= 3 && txtVal <= 1440 && txtVal%1===0) || (txtVal.toUpperCase() == "Default".toUpperCase()))
NoStressDeveloper
  • 491
  • 3
  • 9
  • 26