views:

1085

answers:

4

Hi, I'm using Asp.Net 2.0. I have a scenario where i need to check a user input against any of two ranges. For e.g. I need to check a textbox value against ranges 100-200 or 500-600. I know that i can hook up 2 Asp.Net RangeValidators to the TextBox, but that will try to validate the input against both the ranges, an AND condition,if you will. CustomValidator is an option, but how would I pass the 2 ranges values from the server-side. Is it possible to extend the RangeValidator to solve this particular problem?

[Update] Sorry I didn't mention this, the problem for me is that range can vary. And also the different controls in the page will have different ranges based on some condition. I know i can hold these values in some js variable or hidden input element, but it won't look very elegant.

+1  A: 

You can use the RegularExpressionValidator with the ValidationExpression property set to

Edit: (whoops, 650 and 201 etc. were valid with the old pattern)

^(1\d{2}|200|5\d{2}|600)$

This will test the entered text for 100-200 and 500-600.

cfeduke
This is a much more elegant solution. Well done. I am terrible with regular expressions.
Kyle B.
i'm not so good with them either, but doesn't this also match 299 and 650, which are outside the range?
korro
Yes, it does. I feel much better about my own answer now :)
Kyle B.
I did go down the RegExp path. But it won't work correctly in this case.Thanks anyways.
HashName
Oh yeah let me fix that. One advantage is the regex syntax will be the same for client side validation as well.
cfeduke
BTW http://www.rubular.com/ is awesome for this stuff.
cfeduke
Wow...that's an awesome site..thank you :)
HashName
+1  A: 

I do not believe this is possible using the standard RangeValidator control.

I did some searching and I believe your best solution is going to be to create your own CustomValidator control which you can include in your project to handle this scenario.

http://www.dotnetjunkies.ddj.com/Article/592CE980-FB7E-4DF7-9AC1-FDD572776680.dcik

You shouldn't have to compile it just to use it in your project, as long as you reference it properly.

Kyle B.
+2  A: 

A CustomValidator should work. I'm not sure what you mean by "pass the 2 ranges values from the server-side". You could validate it on the server-side using a validation method like this:

void ValidateRange(object sender, ServerValidateEventArgs e)
{
    int input;
    bool parseOk = int.TryParse(e.Value, out input);
    e.IsValid = parseOk &&
                ((input >= 100 || input <= 200) ||
                (input >= 500 || input <= 600));
}

You will then need to set the OnServerValidate property of your CustomValidator to "ValidateRange", or whatever you happen to call it.

Is this the sort of thing you're after?

Ty
A: 

I extended the BaseValidator to achieve this. Its fairly simple once you understand how Validators work. I've included a crude version of code to demonstrate how it can be done. Mind you it's tailored to my problem(like int's should always be > 0) but you can easily extend it.

    public class RangeValidatorEx : BaseValidator
{

    protected override void AddAttributesToRender(System.Web.UI.HtmlTextWriter writer)
    {
        base.AddAttributesToRender(writer);

        if (base.RenderUplevel)
        {
            string clientId = this.ClientID;

            // The attribute evaluation funciton holds the name of client-side js function.
            Page.ClientScript.RegisterExpandoAttribute(clientId, "evaluationfunction", "RangeValidatorEx");

            Page.ClientScript.RegisterExpandoAttribute(clientId, "Range1High", this.Range1High.ToString());
            Page.ClientScript.RegisterExpandoAttribute(clientId, "Range2High", this.Range2High.ToString());
            Page.ClientScript.RegisterExpandoAttribute(clientId, "Range1Low", this.Range1Low.ToString());
            Page.ClientScript.RegisterExpandoAttribute(clientId, "Range2Low", this.Range2Low.ToString());

        }
    }

    // Will be invoked to validate the parameters 
    protected override bool ControlPropertiesValid()
    {
        if ((Range1High <= 0) || (this.Range1Low <= 0) || (this.Range2High <= 0) || (this.Range2Low <= 0))
            throw new HttpException("The range values cannot be less than zero");

        return base.ControlPropertiesValid();
    }

    // used to validation on server-side
    protected override bool EvaluateIsValid()
    {
        int code;
        if (!Int32.TryParse(base.GetControlValidationValue(ControlToValidate), out code))
            return false;

        if ((code < this.Range1High && code > this.Range1Low) || (code < this.Range2High && code > this.Range2Low))
            return true;
        else
            return false;
    }

    // inject the client-side script to page
    protected override void OnPreRender(EventArgs e)
    {
           base.OnPreRender(e);

           if (base.RenderUplevel)
           {
               this.Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "RangeValidatorEx", RangeValidatorExJs(),true);
           }
    }


    string RangeValidatorExJs()
    {
        string js;
        // the validator will be rendered as a SPAN tag on the client-side and it will passed to the validation function.
        js = "function RangeValidatorEx(val){ "
        + " var code=document.getElementById(val.controltovalidate).value; "
        + " if ((code < rangeValidatorCtrl.Range1High && code > rangeValidatorCtrl.Range1Low ) || (code < rangeValidatorCtrl.Range2High && code > rangeValidatorCtrl.Range2Low)) return true; else return false;}";
        return js;
    }


    public int Range1Low
    {
        get {
            object obj2 = this.ViewState["Range1Low"];

            if (obj2 != null)
                return System.Convert.ToInt32(obj2);

            return 0;

        }
        set { this.ViewState["Range1Low"] = value; }
    }

    public int Range1High
    {
        get
        {
            object obj2 = this.ViewState["Range1High"];

            if (obj2 != null)
                return System.Convert.ToInt32(obj2);

            return 0;

        }
        set { this.ViewState["Range1High"] = value; }
    }
    public int Range2Low
    {
        get
        {
            object obj2 = this.ViewState["Range2Low"];

            if (obj2 != null)
                return System.Convert.ToInt32(obj2);

            return 0;

        }
        set { this.ViewState["Range2Low"] = value; }
    }
    public int Range2High
    {
        get
        {
            object obj2 = this.ViewState["Range2High"];

            if (obj2 != null)
                return System.Convert.ToInt32(obj2);

            return 0;

        }
        set { this.ViewState["Range2High"] = value; }
    }
}
HashName
You may want to check IsClientScriptRegistered before calling RegisterScriptBlock..
HashName