ASP.NET & a Regular Expression Validator

30 05 2010

Right so this is my second blog.  Just last week I was struggling with using an ASP.NET built in validator control to validate a text box control for values between certain amounts and that it must be a decimal number (I also had one for “required field”).

My mission was to join all three seperate validation controls into one but in the end only joined two of them which was the “between values” and “must be decimals”.  I could also join the third one but was lazy so don’t judge me.

I tried to first see if I can join, in a regular expression,  the “only decimals” and “required field” validations but found that only the “required field” validator control can return a true or false for null or !null text boxes.  So it didn’t matter even if i tried more because this block me instantly (I’m using the validation control where you can add your own regular expression for the validation criteria). 

I then tried to see if I can join the “only decimal” and “between values” validator controls with a regular expression but in the end this was a dead end because my “between values” is set dynamically through my code behind page from database values.  If one were able to build such an expression with dynamically set “between values” it would be an enormous not to mention VERY complicated expression. 

So with all this done I decided to just use the ASP.NET custom validator control and use client script to do the validation for both the “decimal only” and “between values”.  Following is a sample of my code:

<asp:TextBox ID=”txtBidAmount” CssClass=”invoer” runat=”server” CausesValidation=”true” ></asp:TextBox>

In my ASPX page:

<script type=”text/javascript”>
      function CheckPrime(sender, args) {
          args.IsValid = true;
          var bid = document.getElementById(‘<%=txtBidAmount.ClientID %>’).value;
          var validateMin = document.getElementById(‘<%=hidValidatorMin.ClientID %>’).value;
          var validateMax = document.getElementById(‘<%=hidValidatorMax.ClientID %>’).value;
          if (bid.match(/^\d+(,)?\d{0,2}?$/) == null)
          { args.IsValid = false; }

          if (parseInt(bid) ‘SmallerThan’ parseInt(validateMin))
{ args.IsValid = false; }

if (parseInt(bid) ‘GreaterThan’ parseInt(validateMax))
{ args.IsValid = false; }
        <asp:RequiredFieldValidator ID=”BidValidatorNotNull” runat=”server”
        <asp:CustomValidator ID=”BidCustomValidator”





Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: