Click to See Complete Forum and Search --> : Form Validation C Sharp


amean_n
05-23-2011, 06:00 AM
Hi there,

I have a form and am trying to get the validation to work correcetly.

The form :

<form id="ContactForm" runat="server" method="post">
<ul class="ContactForm">
<li>
<label class="Label">
First Name:
</label>
<asp:TextBox CssClass="formField" MaxLength="50" ID="txtFirstName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvFirstName" runat="server" ErrorMessage="'First Name' must contain a valid entry"
ControlToValidate="txtFirstName" Display="None"></asp:RequiredFieldValidator>
<asp:Label ID="lblFirstNameRequired" runat="server"></asp:Label></li>
<li>
<label class="Label">
Surname:
</label>
<asp:TextBox CssClass="formField" MaxLength="50" ID="txtSurname" runat="server"></asp:TextBox><asp:RequiredFieldValidator
ID="rfvSurname" runat="server" ErrorMessage="'Surname' must contain a valid entry"
ControlToValidate="txtSurname" Display="None"><span class="error">required</span></asp:RequiredFieldValidator>
<asp:Label ID="lblSurnameRequired" runat="server"></asp:Label>
</li>

</ul>

<asp:Button ID="btnSubmit" ToolTip="Submit form" CssClass="btnSubmitForm" runat="server"
CausesValidation="true" Text="Submit" OnClick="btnSubmit_Click" />

</form>

And the C# logic behind it.

protected void btnSubmit_Click(object sender, EventArgs e)
{

//Data Validation

if (txtFirstName.Text.Length < 1)
{
lblFirstNameRequired.Text = "Required";

}
else
{
if (txtSurname.Text.Length < 1)
{
lblSurnameRequired.Text = "Required";
}



On the submit button being clicked I would like the logic to validate the form.

So far I ahve this, however I cant get it to work correctly.

Any ideas or suggestions as to why and what I should be doing?

Thanks/

developerguru
05-23-2011, 06:38 AM
Just change the logic for btnSubmit_Click

if (txtFirstName.Text.Length < 1)
{
lblFirstNameRequired.Text = "Required";



if (txtSurname.Text.Length < 1)
{
lblSurnameRequired.Text = "Required";
}

}

else

{

type the code that has to followed or else leave it blank.
}

amean_n
05-23-2011, 08:39 AM
Hi developerguru, thanks for your response, however using the code you supplied I still have no joy :(

Thanks.

ryanbutler
05-23-2011, 01:48 PM
Should be able to tap into the IsValid property for the page:

if(!IsValid){
//send your email
}

The rest should be handled internally by .NET framework.