server side validation in asp.net application not working
-
19-04-2021 - |
Question
I am putting server side validation but seems it's not working in the way it should. Below is sample code
//Validation
private void validation()
{
if (txtFName.Text == string.Empty) { Alert("Invalid Name"); return; }
if (txtLName.Text == string.Empty) { Alert("Invalid Name"); return; }
}
// Alert mesage
public void Alert(string msg)
{
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script
type='text/javascript'>alert('" + msg + "');</script>");
}
In my button next click event I am calling this function like
protected void button_Click(object sender, EventArgs e)
{
validation();
}
Surprisingly, even though I don't enter anything in the texbox (means textbox is empty) ... no alert is coming. Whereas, it should alert.
Can someone point me what I am doing wrong. Appreciate your help.
EDIT:
Most weired thing is that, the same code work fine in other page(s). it alerts fine if the fields are empty or validation failing. Not sure what wrong with this page.
Fe pointer like ... This particular aspx page ... has lot of user controls and those controls ascx page have Javascript. I that could be any issue
Solution
I just tried following code.
protected void Button1_Click(object sender, EventArgs e)
{
validation();
}
private void validation()
{
Alert("Invalid Name");
}
// Alert mesage
public void Alert(string msg)
{
ClientScript.RegisterStartupScript(typeof(Page), "SymbolError", "<script type='text/javascript'>alert('" + msg + "');</script>");
}
seem like everything is working fine. check out this see if there is any settings issue. (not sure i m just doing trial and error).
http://bytes.com/topic/asp-net/answers/518330-clientscript-registerstartupscript
OTHER TIPS
i sussgest you to use Asp.net Validation controls, such as Required field validator, Compare validator. as the framework will do all the thing for you. then why your going to validate on your own. ?
in aspx
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="InvalidName" ControlToValidate="TextBox1"></asp:RequiredFieldValidator>
if you want to show all your validation in to message box or summary, you can use validation summary control
<asp:ValidationSummary ID="ValidationSummary1" runat="server" ShowMessageBox="True" />
Even with Scriptmanager
it didn't worked out ... o, my solution was ... I just changed the validation method a bit and it worked out great ... like below
private bool validation()
{
if (txtFName.Text == string.Empty) { Alert("Invalid Name"); return false; }
if (txtLName.Text == string.Empty) { Alert("Invalid Name"); return false; }
}