Form field with validation still lets user submit form with empty value...

I have a text box that a user is to enter a quantity.  I have validation working so that they have to enter an integer, however, the form will still submit if the text box for quantity is left blank.  The field isn't required, so how do I check to make sure that the user doesn't submit a blank value on top of making sure they enter an integer?  This is what I have so far...

<asp:TextBox ID="SpclBioQty" runat="server" Columns="5" Width="33px"></asp:TextBox>

<asp:CompareValidator ID="SpclBioQtyValidator" runat="server" ErrorMessage="*Data must be a number" ControlToValidate="SpclBioQty" Type="Integer" Operator="DataTypeCheck">


Never make important decisions on a Monday!
10/1/2008 4:34:11 PM 91979 articles. 4 followers. Follow

14 Replies

Similar Articles

[PageSpeed] 47

You are missing

ControlToCompare Attribute of Compare Validator.


Please remember to click “Mark as Answer” on the post that helps you

Best Regards
Brij Mohan
10/1/2008 4:49:46 PM

Changed my code to this (staight out of my 3.5 book) and it still lets the form submit with an empty value... however, if I try to enter -2, it does catch that this value is less than zero.  What am I missing? 

<asp:TextBox ID="PocketFolderQty" runat="server" Columns="5" Width="33px"></asp:TextBox>

<asp:CompareValidator ID="PocketFolderQtyValidator" runat="server"




ValueToCompare="0"> </asp:CompareValidator>


Never make important decisions on a Monday!
10/1/2008 5:13:35 PM


Note   If the input control is empty, no validation functions are called and validation succeeds. Use a RequiredFieldValidator control to prevent the user from skipping an input control.


10/1/2008 5:37:17 PM

Argh...  well, at least I understand now.  My silly book says it will work.  Thank you NC01... saved me a hour of beating my head on the desk trying to figure out why.  Unfortunately, the field isn't a required field, so I don't want to use a requiredfieldvalidator.  So, I guess they'll be able to enter a "NULL" value if they don't enter a qty... 

Never make important decisions on a Monday!
10/1/2008 5:46:31 PM

You can use javascript to overcome this issue the code will be something like below

 in the code behind add

Button1.Attributes.Add("onclick", "return func()");

and in the .aspx page include the following script

<script language="javascript">

function func()


if (document.getElementById("TextBox1").value == '')


alert('Blank Not Allowed
!')return false;




10/1/2008 5:47:44 PM

Why would it necessarily have to be a required field? If you want to require a value in it, just add a RequiredFieldValidator. All that's going to do is not let them submit the page without a value there. They could just place a "0" in it, in fact you could default it to "0" if empty like this:

<asp:TextBox ID="PocketFolderQty" runat="server" Columns="5" Width="33px" onfocus="if ( this.value == '0' ) {this.value = '';}" onblur="if ( this.value.length <= 0 ) {this.value = '0';}"></asp:TextBox>

Note that I attached event handlers to the element in the HTML declaration. This will work, but will produce a compiler warning. The proper way to do this for a server control is in the Page_Load handler of the server-side code like this:
 PocketFolderQty.Attributes.Add("onfocus", "if ( this.value == '0' ) {this.value = '';}");
 PocketFolderQty.Attributes.Add("onblur", "if ( this.value.length <= 0 ) {this.value = '0';}");


10/1/2008 6:03:59 PM

hmm interesting... I dont' know much about javascript...

getting a message saying   Expected';'   on this line of code...   alert('Blank Not Allowed!')return false;

Never make important decisions on a Monday!
10/1/2008 6:05:43 PM

check this

alert('Blank Not Allowed!');

return false;

10/1/2008 6:29:17 PM

Did you try the code that I posted? That would seem to me to be a heck of a lot more unobtrusive than validating the TextBox twice.



10/1/2008 6:34:15 PM

 I just want to point out that you could possibly bypass the text box all together (never gains focus) by using a mouse which would prevent onfocus and onblur from being executed. A javascript function that executes when the button is clicked (onClick) or when a form is submitted (onSubmit) could be created that checks to see if the textbox is empty, and if so, load it with a zero (0)

If only everything was easy as “Hello World”

Please remember to click “Mark as Answer” on the post that helps you. This can be beneficial to other community members reading the thread.
10/1/2008 6:39:04 PM
vista7.. well, it doesn't throw an error anymore, but it doesn't prevent the space from inserting either.  Here's my code from the code behind... did I add it wrong?  

Protected Sub PocketFolderSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles PocketFolderSubmit.ClickPocketFolderSubmit.Attributes.Add("onclick", "return func()")


End Sub

Never make important decisions on a Monday!
10/1/2008 6:40:18 PM

NC01 - Yes, tried it too  here's my code from the code behind.. but nothing happenened when I clicked the button without entering a value

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

PocketFolderQty.Attributes.Add("onfocus", "if ( this.value == '0' ) {this.value = '';}")

PocketFolderQty.Attributes.Add("onblur", "if ( this.value.length <= 0 ) {this.value = '0';}")

End Sub

Never make important decisions on a Monday!
10/1/2008 6:41:45 PM

All that code does is take care of when the TextBox gains or loses the focus. If you want the TextBox filled on the button click, add this to the Page_Load handler also.

Dim clickHandler As String = String.Format("if ( document.getElementById('{0}').value.length <= 0 ) {document.getElementById('{1}').value = '0';}", PocketFolderQty.ClientID, PocketFolderQty.ClientID)
Button1.Attributes.Add("onclick", clickHandler)


10/1/2008 6:53:31 PM

change the if condition to

if ((document.getElementById("TextBox1").value == ' ')||(document.getElementById("TextBox1").value == ''))

10/1/2008 7:03:42 PM

Similar Artilces:

validation of form field before submitting the form
Hi, I am designing a workflow for which i have to do form field validation on click of submit button in request form, how this can be achieved in user app 3.7. It is urgent. Thanks, Debaditya Ghosh. -- debaditya_ghosh3 ------------------------------------------------------------------------ On 02/05/2010 03:26 PM, debaditya ghosh3 wrote: > > Hi, > > I am designing a workflow for which i have to do form field > validation on click of submit button in request form, how this can be > achieved in user app 3.7. It is urgent. > > Thanks, ...

Submitting Web forms fields to sql database by clicking on SUBMIT FORM and sending the form fields to email box
I have a created or designed a form to be stored in a SQL database table and at the same time when a user clicks on SUBMIT button the form fields will automatically goto the visitor email address immediately. Also i have created a database with tables for each of this forms Pls help i have over 10 forms designed but the problem of submitting them to the table database and the user email address is the challenge now.... You ned to familiarise yourself with the basics of database access in ASP.NET.  There are free tutuorials here:

Form gets submitted even with wrong values
  I have created one webform in, when i enter the fields, all validations are working e.g: zipcode should be numeric, password > 6 etc... But even if i put wrong values in fields, validation errors get displayed then too i am able to submit the form and values gets stored in DB, where could be the gap !! ...hemen. Make sure you have your submit button set with CausesValidation="true"Scott was here... In your button click event, make sure your first line of code is...  if(!Page.IsValid){return;}   This will force the exit of the event prior to ...

form.submit() not submitting form.
 I have an aspx that contains an ascx. The ascx is a list of files that the user can click on to open. The code around this looks like:         private void openAttachedFile(string fileName)        {            string appPath = ConfigurationManager.AppSettings["AttachmentPath"].ToString() + @"\" + fileName;            FileStream fs = File.OpenRead(appPath);     ...

Request.Form does not get form values
Hi guys, I am new in ASP.NET 2.0 I am stuck with request.form problem I have simple asp:textbox and asp:button nested in the form with runat=server property, but when I want to get textbox value and response.write to page it gets empty, please look at code what do I do wrong?         <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>        <asp:Button ID="Button1" runat="server" Text="Button" />------------------------------------------------------------------------------------------...

After form submitted, how do I get one of the submitted values to display as a label
I can never seem to get this to work the right way.  I have a basic form that once a user submits, I want to display a label with the value they selected.  Do I need to re-query the db to get that value?  What's the easiest most efficient way to display a message indicating the value they submitted? Never make important decisions on a Monday! You can use viewstate. If you need it on multiple pages, then use session variable. A quick look here would be helpful.

getting values from a web form to windows form
Hot Requirement ..... Is there any possible of getting values from a web form to windows form ????? Yes One way i to use the WebRequest and WebResponse classes of the System.Net namespace. For example:  WebRequest request = WebRequest.Create("URL of the web page); WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream()); string content = reader.ReadLine(); ....    Reza Nassabehwww.professionalcsharp.comDon't forget to click "Mark as Answer" on the post that helped you. That way fut...

forms and form validation
am new to asp. i have recently been given the task of redisigning an existing website. the old site included a few forms which i have incorporated into the new site layout. unfortunately, since the redesign, the forms no longer work. i have tried to be as detailed as possible, i am quite sure that all the links are in order. i am assuming that their must be something simple that i have neglected as i have not changed the .js files or the path locations. please advise. Thank you. Hi primalxx, Please let us know, what is not working, why it is not working, and what kind of error...

submit form with empty values
Hi everybody I am developing an automatic xForms generator from monitoring questionnaires defined in another application. It is working fine up to this stage, except that I cannot figure out how to be able to submit the form when fields are left empty (and the type is not a string). I basically have bind elements like: <xf:bind nodeset="./*/REPORT_FIELD_TEMP[@REPORT_FIELD_CODE='1103721']/ @TEXT" id="RT1103721" type="xsd:integer">. which is referred later in the form as: <xf:input class="OnOneLine" bind="RT1103721"&g...

How to Pass data to pop up form, allow user to add new value, pass new value back to form to do Insert
I have a grid view that shows the user the last meter readings (hours) for several generators. The meter readings need to be added daily.  I would like the user to be able to select the meter record from the grid view and have a pop up javascript form open that would allow the user to enter a new meter reading. Then after I do validation, do an insert of the new reading to the database. Is that a reasonable way of doing what I want? If not, can you give me a suggestion as to how to do it differently. Thanks. Hi..   Instead of opening window to ente...

how i can get the one form variable values in other forms?????
iam going to pass values of one form to another formlike asfollows.. f1=CType(Context.Handler ,f1);here f1 is form object this will be used in some other form.iam try ing to use to global variables of first form in to second form.while compilation it show s an error like as follws:"The name 'CType' does not exist in the class or namespace 'PassingValuesForms.Form2'can you giv aslo pls..thanks in advance..ramsCheersRam MCP CType is for the VB.NET language exclusively. By adding a semicolon to your code, I'm guessing you are using C#.CType provides VB users with typecasting. In C#, the lang...

User Control Form validates parent page form ?
Hello, small problem I found after using a user control I made. The user control I made consists of a small form that I place in the footer of my application. For some reason whenever I press the submit button on the control form and there is another form on the parent page (where the control is placed) the main form gets validated and not the control form. Is there any way to specify that only the control form is to be validated ? (Client side) Thanks. When you submit the page, validation runs on ALL validators on the page. It has no idea that your controls are in a user control....

Submitting value from a hidden form field
I have a form inserting into an access database, 1 of the fields is hidden and required. When I click submit the insert fails, if I change the visible value to "true" the insert succeeds. I know this is probably really simple but I can't figure it out. If you set a controls visibility to false then it doesn't appear in the rendered HTML, therefore your hidden field won't be there at all (check the HTML source). In order to make a control still contain a value but be readonly try using the enabled property and set it to fale instead eg <asp:TextBox id="myTextB...

Forms or No Forms
Hope this isn't a repeat.  I looked and didn't find anything. Say for example you had a web page with around 20 fields retrive and update to a database with differing datatypes.  Some fields will have some special controls (dropdowns, radios, buttons, etc) that interact with other parts of the page.  What is the best and/or most efficient code to make the page. Would you use a Formview bound to a standard SQL connection and edit the templates. Use a Formview bound to an Object Data Source and edit within the templates. Or use an Object Data Source and bind the...

Web resources about - Form field with validation still lets user submit form with empty value... -

Cross-validation (statistics) - Wikipedia, the free encyclopedia
is a model validation technique for assessing how the results of a statistical analysis will generalize to an independent data set. It is mainly ...

Serena Williams eyes history, Caroline Wozniacki craves validation in women's US Open final
As Serena Williams eyes another slice of tennis history, Caroline Wozniacki is craving validation with a watershed US Open final triumph on Sunday ...

Travers Duncan asks High Court to strike down ICAC validation laws
ICAC could be sent back to the High Court as a challenge to new laws validating corruption findings looms.

Adam Scott proclaims Texas win as validation of No.1 ranking
... No.1 golfer, beating American Jason Dufner in the third hole of a play-off at the Colonial event. "It's a good feeling and maybe some validation ...

Hollande to sign gay marriage bill after Constitutional Council's validation
Hollande to sign gay marriage bill after Constitutional Council's validation People's Daily Online ... 26, 27, 28, 29, 30, 31. Jan, Feb, Mar, ...

Marketers, Get Ready for the 'Validation Era'
The public brands included has been engaging in a "friends" arms race. But there are signs that we know we overdid it.

Validation and Uncertainty
What an extraordinary conversation I had recently on Twitter. It started with Neil Killick’s statement that we should not consider our stories ...

Nvidia Icera 410 LTE Modem Passes AT&T Network Validation
... Today's news is a small step and logical precursor toward both goals, Nvidia's Icera 410 LTE and HSPA+ baseband has passed AT&T's network validation ...

Ting’s Q1 Subscriber Growth Suffers from Sprint’s New Unlocking Validation Process
Back in February, Sprint updated the process it uses to validate unlocked devices that customers want to utilize on other carriers or one of ...

[Android M Feature Spotlight] Stricter APK Validation Now Actually Checks If All Of An APK's Files Are ...
While you might file this one under "really? We weren't doing this already?" if you're a security expert, Google has added stricter validation ...

Resources last updated: 12/15/2015 9:22:08 PM