Search code examples
asp.netvalidationautopostbacktextchanged

RangeValidator doesn't validate on AutoPostBack


My problem is that the range validator doesn't validate when Text_changed event occur on AutoPostBack.

my code is the following :

public string s;
protected void Page_Load(object sender, EventArgs e)
{...
         TextBox textbox = new TextBox();
         textbox.TextChanged += textbox_TextChanged;
         textbox.ID = p.IDProduct.ToString();
         textbox.AutoPostBack = true;

         RangeValidator rangev = new RangeValidator();
         rangev.ControlToValidate = p.IDProduct.ToString();
         rangev.Type = ValidationDataType.Integer;
         rangev.MinimumValue = "0";
         rangev.MaximumValue = "100";
         rangev.ErrorMessage = "*"; 

...} 

void textbox_TextChanged(object sender, EventArgs e)
{
        s=((TextBox)sender).Text
}

The variable "s" gets some values that are not allowed, like text("asdf") or numbers that are not in range 1-100 ("207" for example). The question is , how to make the range validator work on autopostback ?

if i remove autopostback , the rangevalidator works. But i don't need to remove it. I want it to work with autopostback because i don't want to refresh the page everytime i make a textchange.


Solution

  • i discovered the answer myself. This is the answer :

    void textbox_TextChanged(object sender, EventArgs e)
    { 
            Page.Validate()
            if(Page.IsValid)
            {
               s=((TextBox)sender).Text
            }
    }