Solved

Regular Expression Validator to Trap non-numeric entry.

Posted on 2012-04-08
9
612 Views
Last Modified: 2012-04-09
<asp:TextBox ID="txtMinPrice" runat="server" Width="45px">
    </asp:TextBox>

           <asp:RegularExpressionValidator ID="valMinPrice" runat="server"
                            ErrorMessage="The Minimum Price needs to be numeric. "
                            ValidationExpression="^\d{0,3}(\.\d{1,2})?$"
                            ControlToValidate="txtMinPrice" SetFocusOnError="true"
                            EnableClientScript="False" Display="Dynamic">
            </asp:RegularExpressionValidator>

Entered abc instead of the number 5.

non-numeric not trapped

What should I change?

Thanks,
0
Comment
Question by:Dovberman
  • 5
  • 3
9 Comments
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37821109
ValidationExpression="^\d+$"
0
 

Author Comment

by:Dovberman
ID: 37821201
That did not work.
Any other suggestions?
Thanks,
0
 
LVL 20

Accepted Solution

by:
BuggyCoder earned 250 total points
ID: 37821479
Well it worked perfectly for me, here is the markup to use:-

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
    
</head>
<body>
    
    <form id="form1" runat="server">
    <asp:TextBox runat="server" ID="txtTest"></asp:TextBox>
    <asp:Button runat="server" ID="btnTest" onclick="btnTest_Click"/>
    <asp:RegularExpressionValidator ID="rgValidator" ControlToValidate="txtTest" ValidationExpression="^\d+$" runat="server" ErrorMessage="Only Numbers Are Allowed!!!"></asp:RegularExpressionValidator>
    </form>
</body>
</html>

Open in new window


And Here is the code behind:-

using System;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnTest_Click(object sender, EventArgs e)
    {
        if(this.IsValid)
        {
            
        }
    }
}

Open in new window

0
 
LVL 23

Assisted Solution

by:basicinstinct
basicinstinct earned 250 total points
ID: 37821779
the problem is not with your regular expression.
the regex you have "^\d{0,3}(\.\d{1,2})?$" allows a an amount between 0 to 999.99

why don't you try a RangeValidator
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:Dovberman
ID: 37822403
To BuggyCoder:

<asp:TextBox ID="txtMinPrice" runat="server" Width="45px"
    onTextChanged = "txtMinPrice_TextChanged" CausesValidation="true">
    </asp:TextBox>

<asp:RegularExpressionValidator ID="valMinPrice" runat="server"
                            ErrorMessage="The Minimum Price needs to be numeric. "
                            ControlToValidate="txtMinPrice" SetFocusOnError="true"
                            EnableClientScript="False" Display="Dynamic"
                            ValidationExpression="^\d+$">
                        </asp:RegularExpressionValidator>

     protected void txtMinPrice_TextChanged(object sender, EventArgs e)

    {
        int Test1 = 0;
       if (this.IsValid)
        {
        Test1 = 1;
        }
    }

Error:

Page.IsValid cannot be called before validation has taken place.
It should be queried in the event handler for a control that has
CausesValidation=True and initiated the postback,
or after a call to Page.Validate.
0
 
LVL 20

Expert Comment

by:BuggyCoder
ID: 37822410
you are applying it in text changed event of text box, this event will fire with every change in textbox data.
Ideally IsValid should be called on button click where we like to validate data before the final submit....

In your case you are making your text box to cause validation, this is not right or a good practice.
Suggest have a button and make its cause validation true and remove causevalidation from textbox....
0
 

Author Comment

by:Dovberman
ID: 37822438
To BasicInstinct

<asp:RangeValidator ID="valMinPrice" runat="server"
                        ErrorMessage="The Minimum Price needs to be numeric and between 1 and 100"
                        MaximumValue="100"
                        MinimumValue="1"
                        ControlToValidate="txtMinPrice" Display="Dynamic" SetFocusOnError="True">
                </asp:RangeValidator>

Error on any value entered except "1.00" or "1".
0
 

Author Comment

by:Dovberman
ID: 37822474
This is what I did that works.  It is complex, but does the job.

I used the TextChanged event. Then disabled the main process button if the entry was not numeric.

Based on
http://www.experts-exchange.com/Programming/Languages/C_Sharp/Q_22806510.html

<asp:TextBox ID="txtMinPrice" runat="server" Width="45px"
    onTextChanged = "txtMinPrice_TextChanged" AutoPostBack="True">
    </asp:TextBox>

Code behind:

 public void txtMinPrice_TextChanged(object sender, EventArgs e)
    {
        lblResult.Text = "";
        string strEntered = txtMinPrice.Text;
        bool blnIsNumeric = IsNumeric(strEntered);
        if (!blnIsNumeric)
        {
            lblResult.Text = "Price must be numeric and between 1.00 and 100.00";
            cmdGetResults.Enabled = false;
         }

        else
        {
            cmdGetResults.Enabled =true;
        }
        return;
    }

     public static bool IsNumeric(string pstrEntry)
            {
                bool isNum;
                double retNum;

                isNum = Double.TryParse(Convert.ToString(pstrEntry),
                    System.Globalization.NumberStyles.Any,
                    System.Globalization.NumberFormatInfo.InvariantInfo, out retNum);

                return isNum;

            }
0
 

Author Closing Comment

by:Dovberman
ID: 37823049
I appreciate the suggestions made and the effort spent.<br /><br />That's why I divided the points evenly.<br /><br />Thanks,
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
I have developed many web applications with asp & asp.net and to add and use a dropdownlist was always a very simple task, but with the new asp.net, setting the value is a bit tricky and its not similar to the old traditional method. So in this a…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now