Custom Validation Controls - how to prevent text box data being used

S

Stephen Adam

Hi there,

I have written a custom validation control which checks to see of an input
field is not empty and contains only numeric data. I was using a regular
expression validation control but was unable to get it fail if a field was
blank.

My problem now is that while my custom validation control will detect if a
field matches my requirement and will display a error message if it doesnt,
it wont stop it from being used and sent to my back end code - so I still
get a nsty crash out if there is an empty field or a field with illegals
chars in it.

So my question is how do I get a custom validation control work in the same
way as a standard validation control and prevent bad input from ever being
sent to the "code behind".

Thanks in advance, i've included the revevant code below.


<%@ Register TagPrefix="CustomValidators" Namespace="CustomValidators"
Assembly="CustomWebControls" %>

<asp:TextBox ID="tbRecordToDelete" Runat="server"></asp:TextBox>

<CustomValidators:NumberValidator
Runat="server"
ErrorMessage="Please Enter a Valid ID Number"
ControlToValidate="tbRecordToDelete"
Display="static"
ID="customValidator1"> </CustomValidators:NumberValidator>


using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Text.RegularExpressions;


namespace CustomValidators
{


// Checks control contains only a number and is not null
public class NumberValidator : System.Web.UI.WebControls.BaseValidator
{

public NumberValidator()
{
base.EnableClientScript = true;
}

protected override bool EvaluateIsValid()
{

Regex isNumberAndNotNull = new Regex("^[0-9][0-9]*$");

string controlValue =
this.GetControlValidationValue(this.ControlToValidate);
if (isNumberAndNotNull.IsMatch(controlValue))
{
return true;
}
else
{
return false;
}
}

}
}
 
S

Scott Allen

Hi Stephen:

You might try the ASP.NET stock RangeValidator control. You could set
the minimum and maximum to Int32.MaxValue and Int32.MinValue if you
are not concerned with the range, but set the Type property to Integer
and it will validate all numbers that fit in a 32 bit int.

For you custom validator, what error message do you get? What does
GetControlValidationValue look like?
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top