Custom Range Validator how-to?

J

jdn

Would appreciate some help, as I am blanking on the best way to do this.

I want to have a Range Validator for a textbox where the Minimum and Maximum values are based on what is entered in a different textbox. So, for instance, if the value in the other textbox is X, then the range validator would check to ensure that the value being validated is between 20-50% of X.

What is the easiest way to do this, in such a way that there can be client-side validation as well? Options I've though of...

1) Create a new control that derives from BaseValidator
2) Create a new control that derives from RangeValidator itself
3) Skip making a new control and have the Maximum and Minimum values of a normal range validator changed in a function every time the text in the other textbox changes and/or loses focus.

3) is 'simpler' in some sense, but seems kind of 'hacky', but I've done neither 1) nor 2) before.

Unless there is some other way of doing it, that I'm not thinking of.

TIA
jdn
 
H

Hermit Dave

User a custom validator.
I had a scenario where i needed to validate the selected value in one
dropdownlist against a value of another dropdownlist's selectedValue.
You can then write both custom server side and client side code (for client
side validation i used RegisterClientSciptBlock) and you specify both server
and client side validation functions... thats about all you need to do... on
submit... the values will be validated based on your code... and your
requirements... popup message or message in span on client side or span
rendered by server side...
even adds it to your summary control for godsake... :)

so its 3... neither 1 nor 2... but a simpler option 3

--
Regards,

HD

Once a Geek.... Always a Geek
jdn said:
Would appreciate some help, as I am blanking on the best way to do this.

I want to have a Range Validator for a textbox where the Minimum and
Maximum values are based on what is entered in a different textbox. So, for
instance, if the value in the other textbox is X, then the range validator
would check to ensure that the value being validated is between 20-50% of X.
What is the easiest way to do this, in such a way that there can be
client-side validation as well? Options I've though of...
1) Create a new control that derives from BaseValidator
2) Create a new control that derives from RangeValidator itself
3) Skip making a new control and have the Maximum and Minimum values of a
normal range validator changed in a function every time the text in the
other textbox changes and/or loses focus.
 
J

jdn

Yeah, I did forget to list that option.

Do you have a link or sample of the specifics of how to do this? I'm
working my way through MSDN etc. and am not sure I am seeing the forest for
the trees, if you know what I mean.

Thanks.

jdn
 
J

Jeffrey Tan[MSFT]

Hi

Thank you for using MSDN Newsgroup! My name is Jeffrey, and I will be
assisting you on this issue.

Based on my understanding, you want to do the validation based on some
runtime condition(Another textbox's text value).
I agree that you should custom validator control to get this done.

===================================
Based on my research, I think you can try the following 3 Steps to get this
done:
1). Create a Custom Valiation control on the web form.
2). Write the Server side validation event handler. Sample code like this:
private void CustomValidator1_ServerValidate(object source,
System.Web.UI.WebControls.ServerValidateEventArgs args)
{
double max, min;
double val=Convert.ToSingle(TextBox2.Text);
min=val*0.2;
max=val*0.5;
double newval=Convert.ToSingle (TextBox1.Text);
args.IsValid=(newval>=min&&newval<=max);
}

3).Register the client validation javascript code, the validation sample
like this:
Set the CustomValidator1's ClientValidationFunction to "clientvalidate"

<script language="javascript">
function clientvalidate(source, args)
{
var val=document.forms[0].item("TextBox2").value;
var min=val*0.2;
var max=val*0.5;

if(args.Value>=min&&args.Value<=max)
{
args.IsValid=true;
}
else
{
args.IsValid=false;
}

}
</script>

Please apply my suggestion above and let me know if it helps resolve your
problem.
Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I am standing by to be
of assistance.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
J

jdn

Yes, that does work.

What I would like to do in the long run is to make this a custom control so that I can drag and drop it (since I will have many of these) and not have to write the javascript out each time I put it on a page, etc.

jdn

----- \"Jeffrey Tan[MSFT]\" wrote: -----


Hi

Thank you for using MSDN Newsgroup! My name is Jeffrey, and I will be
assisting you on this issue.

Based on my understanding, you want to do the validation based on some
runtime condition(Another textbox's text value).
I agree that you should custom validator control to get this done.

===================================
Based on my research, I think you can try the following 3 Steps to get this
done:
1). Create a Custom Valiation control on the web form.
2). Write the Server side validation event handler. Sample code like this:
private void CustomValidator1_ServerValidate(object source,
System.Web.UI.WebControls.ServerValidateEventArgs args)
{
double max, min;
double val=Convert.ToSingle(TextBox2.Text);
min=val*0.2;
max=val*0.5;
double newval=Convert.ToSingle (TextBox1.Text);
args.IsValid=(newval>=min&&newval<=max);
}

3).Register the client validation javascript code, the validation sample
like this:
Set the CustomValidator1's ClientValidationFunction to "clientvalidate"

<script language="javascript">
function clientvalidate(source, args)
{
var val=document.forms[0].item("TextBox2").value;
var min=val*0.2;
var max=val*0.5;

if(args.Value>=min&&args.Value<=max)
{
args.IsValid=true;
}
else
{
args.IsValid=false;
}

}
</script>

Please apply my suggestion above and let me know if it helps resolve your
problem.
Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I am standing by to be
of assistance.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
J

Jeffrey Tan[MSFT]

Hi jdn,

Thanks for your feedback. Sorry for letting you wait for so long time.
I have seen your concern, you want to make all the functions into a custom
control for other customer to use.

===========================
I have writen a sample project for your concern. I think you should
generating all the client javascript code dynamicly.

You can try the following Steps to see if it helps resolve your issue:
1). Create a Web Control Library project, which inherited from
System.Web.UI.WebControls.CustomValidator class
2). Create a new property Controltodependid for the user to input the
control id whose value you want to retrieve.
3). Override its OnLoad method and use Page.RegisterClientScriptBlock to
dynamic generate the Client validation script

Sample full code like this:
public class WebCustomControl1 : System.Web.UI.WebControls.CustomValidator
{
protected override void Render(HtmlTextWriter output)
{
base.Render(output);
output.Write(Text);
}

protected override void OnLoad(EventArgs e)
{
base.OnLoad (e);

StringBuilder sb=new StringBuilder();
sb.Append("<script language=\"javascript\">");
sb.Append("function ");
sb.Append(this.ClientValidationFunction.ToString());
sb.Append("(source, args)");
sb.Append("{");
sb.Append("var val=document.forms[0].item(\"");
sb.Append(this.Controltodependid);
sb.Append("\").value;");
sb.Append("var min=val*0.2;");
sb.Append("var max=val*0.5;");
sb.Append("if(args.Value>=min&&args.Value<=max)");
sb.Append("{");
sb.Append("args.IsValid=true;");
sb.Append("}else{");
sb.Append("args.IsValid=false;");
sb.Append("}}");
sb.Append("</script>");

this.Page.RegisterClientScriptBlock("script",sb.ToString());
}

string controltodependid;

public string Controltodependid
{
get
{
return controltodependid;
}
set
{
controltodependid=value;
}
}
}

When using this custom control, you should set its Controltodependid
property to specify the textbox you want to retrive value. You also should
set ClientValidationFunction to specify the client validation function name.

==============================
Please apply my suggestion above and let me know if it helps resolve your
problem.

Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I will try my best to
help you.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
J

jdn

So then to make the range changeable, you would make properties that you could set (so I wouldn't want to hard-code in 'val * .2' etc. since the range would vary....otherwise the control isn't very useful) and then modify the OnLoad accordingly

jd

----- \"Jeffrey Tan[MSFT]\" wrote: ----


Hi jdn

Thanks for your feedback. Sorry for letting you wait for so long time
I have seen your concern, you want to make all the functions into a custom
control for other customer to use

==========================
I have writen a sample project for your concern. I think you should
generating all the client javascript code dynamicly

You can try the following Steps to see if it helps resolve your issue
1). Create a Web Control Library project, which inherited from
System.Web.UI.WebControls.CustomValidator clas
2). Create a new property Controltodependid for the user to input the
control id whose value you want to retrieve
3). Override its OnLoad method and use Page.RegisterClientScriptBlock to
dynamic generate the Client validation scrip

Sample full code like this
public class WebCustomControl1 : System.Web.UI.WebControls.CustomValidato

protected override void Render(HtmlTextWriter output

base.Render(output)
output.Write(Text)


protected override void OnLoad(EventArgs e

base.OnLoad (e)

StringBuilder sb=new StringBuilder()
sb.Append("<script language=\"javascript\">")
sb.Append("function ")
sb.Append(this.ClientValidationFunction.ToString())
sb.Append("(source, args)")
sb.Append("{")
sb.Append("var val=document.forms[0].item(\"")
sb.Append(this.Controltodependid)
sb.Append("\").value;")
sb.Append("var min=val*0.2;")
sb.Append("var max=val*0.5;")
sb.Append("if(args.Value>=min&&args.Value<=max)")
sb.Append("{")
sb.Append("args.IsValid=true;")
sb.Append("}else{")
sb.Append("args.IsValid=false;")
sb.Append("}}")
sb.Append("</script>")

this.Page.RegisterClientScriptBlock("script",sb.ToString())


string controltodependid

public string Controltodependi

ge

return controltodependid

se

controltodependid=value




When using this custom control, you should set its Controltodependid
property to specify the textbox you want to retrive value. You also should
set ClientValidationFunction to specify the client validation function name

=============================
Please apply my suggestion above and let me know if it helps resolve your
problem

Thank you for your patience and cooperation. If you have any questions or
concerns, please feel free to post it in the group. I will try my best to
help you

Best regards
Jeffrey Ta
Microsoft Online Partner Suppor
Get Secure! - www.microsoft.com/securit
This posting is provided "as is" with no warranties and confers no rights
 
J

Jeffrey Tan[MSFT]

Hi jdn,

Yes, you are right. You should expose the range rate as 2 properties, then
the your control customer can set them properly and use it freely.
Also, if you want to make your control more like realistic control, I think
you can add more logic into your control:

1). In OnLoad method, judge the EnableClientScript property to determine if
render the client javascript code.
2). Encapsulate the server side validation logic in your control, then your
control user need not add any programming logic to use.
To get this done, I think you should override OnServerValidate method and
do the server side validation.
3). Just as you point out, Add lower and upper range rate as properties for
user in your control.

Sample code like this:
public class WebCustomControl1 : System.Web.UI.WebControls.CustomValidator
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad (e);

if(this.EnableClientScript==true)
{
StringBuilder sb=new StringBuilder();
sb.Append("<script language=\"javascript\">");
sb.Append("function ");
sb.Append(this.ClientValidationFunction.ToString());
sb.Append("(source, args)");
sb.Append("{");
sb.Append("var val=document.forms[0].item(\"");
sb.Append(this.Controltodependid);
sb.Append("\").value;");
sb.Append("var min=val*0.2;");
sb.Append("var max=val*0.5;");
sb.Append("if(args.Value>=min&&args.Value<=max)");
sb.Append("{");
sb.Append("args.IsValid=true;");
sb.Append("}else{");
sb.Append("args.IsValid=false;");
sb.Append("}}");
sb.Append("</script>");

this.Page.RegisterClientScriptBlock("script",sb.ToString());
}
}

string controltodependid;
float lower_range;
float upper_range;

public float Lower_Range
{
get
{
return lower_range;
}
set
{
lower_range=value;
}
}

public float Upper_Range
{
get
{
return upper_range;
}
set
{
upper_range=value;
}
}

public string Controltodependid
{
get
{
return controltodependid;
}
set
{
controltodependid=value;
}
}

protected override bool OnServerValidate(string value)
{
bool result=base.OnServerValidate (value);
double max, min;
TextBox tb=(TextBox)this.Page.FindControl(this.Controltodependid);
double val=Convert.ToSingle(tb.Text);
min=val*0.2;
max=val*0.5;
double newval=Convert.ToSingle (value);
this.IsValid=(newval>=min&&newval<=max);
return result&&this.IsValid;
}

protected override void Render(HtmlTextWriter output)
{
base.Render(output);
output.Write(Text);
}
}

==============================================================
If it does not work, please feel free to tell me.
Have a nice day!!

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
J

jdn

Shouldn't min and max then be tied into Upper_Range and Lower_Range, both in OnServerValidate and the client side script in OnLoad? Otherwise, I don't see how they do anything, right

jd

----- \"Jeffrey Tan[MSFT]\" wrote: ----


Hi jdn

Yes, you are right. You should expose the range rate as 2 properties, then
the your control customer can set them properly and use it freely
Also, if you want to make your control more like realistic control, I think
you can add more logic into your control

1). In OnLoad method, judge the EnableClientScript property to determine if
render the client javascript code
2). Encapsulate the server side validation logic in your control, then your
control user need not add any programming logic to use
To get this done, I think you should override OnServerValidate method and
do the server side validation
3). Just as you point out, Add lower and upper range rate as properties for
user in your control

Sample code like this
public class WebCustomControl1 : System.Web.UI.WebControls.CustomValidato

protected override void OnLoad(EventArgs e

base.OnLoad (e)

if(this.EnableClientScript==true

StringBuilder sb=new StringBuilder()
sb.Append("<script language=\"javascript\">")
sb.Append("function ")
sb.Append(this.ClientValidationFunction.ToString())
sb.Append("(source, args)")
sb.Append("{")
sb.Append("var val=document.forms[0].item(\"")
sb.Append(this.Controltodependid)
sb.Append("\").value;")
sb.Append("var min=val*0.2;")
sb.Append("var max=val*0.5;")
sb.Append("if(args.Value>=min&&args.Value<=max)")
sb.Append("{")
sb.Append("args.IsValid=true;")
sb.Append("}else{")
sb.Append("args.IsValid=false;")
sb.Append("}}")
sb.Append("</script>")

this.Page.RegisterClientScriptBlock("script",sb.ToString())



string controltodependid
float lower_range
float upper_range

public float Lower_Rang

ge

return lower_range

se

lower_range=value



public float Upper_Rang

ge

return upper_range

se

upper_range=value



public string Controltodependi

ge

return controltodependid

se

controltodependid=value



protected override bool OnServerValidate(string value

bool result=base.OnServerValidate (value)
double max, min
TextBox tb=(TextBox)this.Page.FindControl(this.Controltodependid)
double val=Convert.ToSingle(tb.Text)
min=val*0.2
max=val*0.5
double newval=Convert.ToSingle (value)
this.IsValid=(newval>=min&&newval<=max)
return result&&this.IsValid


protected override void Render(HtmlTextWriter output

base.Render(output)
output.Write(Text)



=============================================================
If it does not work, please feel free to tell me
Have a nice day!

Best regards
Jeffrey Ta
Microsoft Online Partner Suppor
Get Secure! - www.microsoft.com/securit
This posting is provided "as is" with no warranties and confers no rights
 
J

Jeffrey Tan[MSFT]

Hi

So sorry for incorrect code. It seems that my source code was overlay by
its original one. Yes, just as you said, we should tied min and max with
Lower_Range and Upper_Range, Here is the correct code:

if(this.EnableClientScript==true)
{
StringBuilder sb=new StringBuilder();
sb.Append("<script language=\"javascript\">");
sb.Append("function ");
sb.Append(this.ClientValidationFunction.ToString());
sb.Append("(source, args)");
sb.Append("{");
sb.Append("var val=document.forms[0].item(\"");
sb.Append(this.Controltodependid);
sb.Append("\").value;");
/////////////////////////////////////////////////////
sb.Append("var min=val*");
sb.Append(this.Lower_Range);
sb.Append(";");
sb.Append("var max=val*");
sb.Append(this.Upper_Range);
sb.Append(";");
/////////////////////////////////////////////////////
sb.Append("if(args.Value>=min&&args.Value<=max)");
sb.Append("{");
sb.Append("args.IsValid=true;");
sb.Append("}else{");
sb.Append("args.IsValid=false;");
sb.Append("}}");
sb.Append("</script>");

this.Page.RegisterClientScriptBlock("script",sb.ToString());
}

protected override bool OnServerValidate(string value)
{
bool result=base.OnServerValidate (value);
double max, min;
TextBox tb=(TextBox)this.Page.FindControl(this.Controltodependid);
double val=Convert.ToSingle(tb.Text);
///////////////////////////////////////////////////////////
min=val*this.Lower_Range;
max=val*this.Upper_Range;
///////////////////////////////////////////////////////////
double newval=Convert.ToSingle (value);
this.IsValid=(newval>=min&&newval<=max);
return result&&this.IsValid;
}

I really hope that my effect can help you. Thanks

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
J

Jeffrey Tan[MSFT]

Hi jdn,

I am glad it makes sense to you.
If you have any further concern, please feel free to post in the group. I
will work with you.

Best regards,
Jeffrey Tan
Microsoft Online Partner Support
Get Secure! - www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,226
Members
46,815
Latest member
treekmostly22

Latest Threads

Top