ASP.NET Client-side vs Server-side Validation - c#

I am constantly getting incorrect info from the "Instructor" at school on this.
For ASP.NET Web Applications, the Validators from the Toolbox like CompareValidator, RangeValidator, RequiredFieldValidator, etc, are those considered Server-Side Validation?
Because we also add a jQuery NuGet package and it gives real time validation when the user tabs, like if the user types a letter when a number is required.
For WPF's in C# I create a Validator Class or use a Library and check validation that way through Static Methods. Should I be doing it this way in ASP.NET as well? Or are the RequiredFieldValidators, etc enough for Server-Side Validation?
Here is an example:
<div class="form-group">
<label class="control-label col-sm-4">Length:</label>
<div class="col-sm-4">
<asp:TextBox ID="txtLength" runat="server" CssClass="form-control" MaxLength="15"></asp:TextBox>
</div>
<div class="col-sm-4">
<asp:RequiredFieldValidator ID="rfvLength" runat="server" ErrorMessage="Length is required"
ControlToValidate="txtLength" CssClass="error" Display="Dynamic" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="rngLength" runat="server" ErrorMessage="Must be between .01 and 10,000"
MaximumValue="10000" MinimumValue=".01" ControlToValidate="txtLength" CssClass="error" Display="Dynamic"
SetFocusOnError="True" Type="Double"></asp:RangeValidator>
</div>
</div>
thanks
******EDIT*****
Guys you are giving unclear or incomplete answers just like my "Instructor" does.
Yes or No please, is this Server-side Validation in ASP.NET?
<div class="form-group">
<label class="control-label col-sm-4">Length:</label>
<div class="col-sm-4">
<asp:TextBox ID="txtLength" runat="server" CssClass="form-control" MaxLength="15"></asp:TextBox>
</div>
<div class="col-sm-4">
<asp:RequiredFieldValidator ID="rfvLength" runat="server" ErrorMessage="Length is required"
ControlToValidate="txtLength" CssClass="error" Display="Dynamic" SetFocusOnError="True"></asp:RequiredFieldValidator>
<asp:RangeValidator ID="rngLength" runat="server" ErrorMessage="Must be between .01 and 10,000"
MaximumValue="10000" MinimumValue=".01" ControlToValidate="txtLength" CssClass="error" Display="Dynamic"
SetFocusOnError="True" Type="Double"></asp:RangeValidator>
</div>
</div>
and then I also add:
protected void btnCalculate_Click(object sender, EventArgs e)
{
if (IsValid)
{
double length = Convert.ToDouble(txtLength.Text);
double width = Convert.ToDouble(txtWidth.Text);
Rectangle r = new Rectangle(length, width);
txtArea.Text = r.Area().ToString("f");
txtPerimeter.Text = r.Perimeter().ToString("f");
txtDiagonal.Text = r.Diagonal().ToString("f");
}
}
Is this correct as Server-side Validation in ASP.NET and am I using the if (IsValid) part correctly?

You are mixing ASP.NET Validation Control and difference between Client side and Server Side validation.
When ASP.NET page renders the Validation Controls RequiredFieldValidator and RangeValidator etc., it automatically creates Client side JavaScript function to perform validation within the browser i.e. client side validation.
IsValid is server side validation feature of ASP.Net Pages by which it verifies whether the Asp.Net Validation Control used in the WebForm/ WebPage had performed the validation, and at the server side code, if all the validation is applied (i.e. if all mandatory fields etc. are entered ) then IsValid becomes true.
Note that is not mandatory to put IsValid in server side code, as the JavaScript functions which are created will do the required validations on the client side.
So, basically ASP.NET Validation Control helps to validate ASP.NET pages from both Client Side and Server Side, and have an advantage compared to plain JavaScript validation.
Another example is JQuery code (JavaScript Library) which can be used to do Client Side validation like validating if textbox's value is empty or not. At the same time JQuery can be used to do server side validation by an AJAX call to a web service method on the server side.

When using the ASP.Net validation server-controls, you still want to double-check that that Page.IsValid before attempting to save the data on the server-side.

According to MSDN, those controls inject some kind of javascript validation at client-side;
By default, the validator controls inject client-side ECMAScript (JavaScript) into the page to perform validation checking in the browser. This gives users instant feedback on validation errors; without the client script, checking for validation errors would require a round trip to the server, which could be slow at times. In fact, you cannot submit the page until the client-side validation succeeds
https://msdn.microsoft.com/en-us/library/a0z2h4sw.aspx
Some controls also have a server validation option, which you can use if you need to:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){
try
{
DateTime.ParseExact(args.Value, "m/d/yyyy",
System.Globalization.DateTimeFormatInfo.InvariantInfo);
args.IsValid = true;
}
catch
{
args.IsValid = false;
}}
You can also check for Page.IsValid

ASP.NET Validation controls can be used in both client and server-side validation. Validation controls always perform validation on the server. They also have complete client-side implementation.
Use the EnableClientScript property to specify whether client-side validation is enabled.

Related

If regularexpressionvalidator returns false launch method in c#

I have a widget for a newsletter in which i use the RegularExpressionValidator to check if the email input is valid. My codebehind is a method that opens an smtp connection and sends an email.
My .aspx looks like this:
<asp:TextBox ID="txtEmail" runat="server" CssClass="form-control newsmail"></asp:TextBox>
<asp:RegularExpressionValidator style="position:absolute; margin-top:50px; margin-left:58px;" ID="RegularExpressionValidator1" runat="server" ErrorMessage="Invalid E-mail" ControlToValidate="txtEmail" ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
<asp:Button ID="submit" runat="server" Text="Submit" CssClass="btn btn-lg btn-success submit" OnClick="submit_Click1" />
and my codebehind has the following method:
protected void submit_Click1(object sender, EventArgs e)
{
....
}
Obviously as it is now, it will try to send the email whether the e-mail is valid or not. Therefore im looking for some kind of conditional expression that takes the RegEx into consideration before it completes the method and sends the e-mail.
I know its possible to do it all in C#, but im fairly new to C#, so this looked like the easiest workaround at this point.
The validators in the ASP.net page can already work as JavaScript in the Browser. When you enable this functionality and the user's browser has JavaScript enabled, then your submit_Click1 method will not even be executed when there is invalid data in the input controls.
If you disable the validators to work at the client side or the user's browser does not have JavaScript enabled, you should check in the code behind that all the validators successfully validated the user input. You can do that by checking the isValid property of the page:
protected void submit_Click1(object sender, EventArgs e)
{
if(Page.IsValid)
{
// All Validators Passed -> Do something
}
else
{
// Some invalid data, do nothing
}
}

ASP.NET Javascript runtime error

I have just started a new ASP.NET web application and I am totally new to everything and after moving a few things round I have been getting this error and I don't understand what it means.
It happens when I go to enter anything in the Password box.
Could someone please help me out on this issue.
EDIT:
<li>
<asp:Label runat="server" AssociatedControlID="Password">Password</asp:Label>
<asp:TextBox runat="server" ID="Password" TextMode="Password" onkeypress="capLock(event)" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="Password" CssClass="field-validation-error" ErrorMessage="The password field is required." />
</li>
Try to do that inside
window.onload = function(){
// code goes here
}
I think you are trying to access DOM even before it is being created.
the document.getElementById('divMayus') is undefined
document.getElementById("divMayus") is returning null or undefined.
You should look at the rendered html and find the div that you are trying to reference to make sure the id is the same as you are trying to reach. Asp.net alters the ids of server controls depending on their containers. So if you moved stuff around, the id may have also been changed.

How to make an asp Validator validate through jQuery/javascript

I've got an asp:RequiredFieldValidator, which checks an asp:TextBox to see if it is blank or not.
On a button press, I would like to make the validator validate the textbox. This must be done through jQuery/javascript, as the button is an html input button.
Any ideas? I've read many resources on the web, but have not managed to accomplish this (i.e. the calling of validation through jquery)
You can trigger validation from JavaScript like this:
var isValid = Page_ClientValidate("");
If you only want to validate controls in a certain group just pass the group name into the function:
var isValid = Page_ClientValidate("GroupName");
Here's a quick example:
<script type="text/javascript">
validateStuff = function(){
return Page_ClientValidate("ValidateTextBox");
}
</script>
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1"
ValidationGroup="ValidateTextBox"
Display="Dynamic"
ErrorMessage="*" ...>
</asp:RequiredFieldValidator>
<input type="button" value="Click Me" onclick="return validateStuff();" />
if its jQuery validation your after - there are few better / easier to implement than this one -> http://bassistance.de/jquery-plugins/jquery-plugin-validation/
All you need is a CustomValidator. Add OnServerValidate for server-side, and ClientValidationFunction to your javascript. Here is a reasonably good intro to CustomValiditors but no jQuery reference: https://web.archive.org/web/20211020145934/https://www.4guysfromrolla.com/articles/073102-1.aspx

Efficient/Easy method to validate for empty text boxes?

I have a about 6 or 7 text boxes which needs to be validated to make sure they are not empty from server side code. So how I usually do this is, check each textbox 1 by 1 to ensure that they are not empty. Are there any other efficient methods to do this? I have searched on SO and have found out that adding all the textboxes to a list and using a for each is a much better method. Are there any other ways that this can be achieved? Thanx a lot in advance :)
Just check them each individually:
if (string.IsNullOrEmpty(this.NameTextBox.Text) ||
string.IsNullOrEmpty(this.AddressLine1TextBox.Text) ||
// etc...
)
{
// Handle me
}
Or possibly:
void CheckTextBox(TextBox textBox)
{
if (textBox == null)
{
throw new ArgumentNullException("textBox");
}
if (string.IsNullOrEmpty(textBox.Text))
{
// Handle me
}
}
void Validate()
{
CheckTextBox(this.FirstNameTextBox);
CheckTextBox(this.AddressLine1TextBox);
CheckTextBox(this.AddressLine2TextBox);
}
7 text boxes really isn't that many - explicitly checking each one keeps it simple and makes sure that others reading your code know what's going on, whereas messing around with collections is adding another layer of indirection, and makes it just slightly less straightforward to debug.
Keep it simple!
I agree with Kragen - your code may look "big" because of all the checks, but you are really writing exactly what the program needs to do in order to validate these things, so any sort of clever approach that reduces the number of lines of code you write isn't actually going to speed things up that much.
Question though: do you have to validate the textbox on the server? If you are only validating that the textbox isn't empty, I'd suggest using client side validation. That will save you server time and bandwidth, since your user won't be allowed to submit the form to your server until their browser has validated that they aren't empty.
You'd still want to validate on the server side (in case they don't have JavaScript enabled on their browser or they are attempting some kind of malicious behaviour).
The native ASP.NET way of client side validation involves adding an ASP.NET validation tag to your ASPX. It's actually quite easy. Here's an example on MSDN:
http://msdn.microsoft.com/en-us/library/aa479013.aspx#aspnet-validateaspnetservercontrols_topic3
I've simplified their code a bit to match your requirements:
<form runat="server">
<asp:TextBox id="TextBox1" runat="server" />
<asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" ErrorMessage="Name is required!" ControlToValidate="TextBox1" />
<asp:TextBox id="TextBox2" runat="server" />
<asp:RequiredFieldValidator id="RequiredFieldValidator2" runat="server" ErrorMessage="Address is required!" ControlToValidate="TextBox2" />
<asp:Button id="Button1" onclick="Button1_Click" runat="server" Text="Button"></asp:Button>
</form>

ASP.NET Custom Validator Client side & Server Side validation not firing

This has not happened to me before, but for some reason both the client and server side validation events are not being triggered:
<asp:TextBox ID="TextBoxDTownCity" runat="server" CssClass="contactfield" />
<asp:CustomValidator ID="CustomValidator2" runat="server" EnableClientScript="true"
ErrorMessage="Delivery Town or City required"
ClientValidationFunction="TextBoxDTownCityClient"
ControlToValidate="TextBoxDTownCity"
OnServerValidate="TextBoxDTownCity_Validate" Display="Dynamic" >
</asp:CustomValidator>
Server-side validation event:
protected void TextBoxDTownCity_Validate(object source, ServerValidateEventArgs args)
{
args.IsValid = false;
}
Client-side validation event:
function TextBoxDCountyClient(sender, args) {
args.IsValid = false;
alert("test");
}
I thought at the least the Server Side validation would fire but no. this has never happened to me before. This has really got me stumped.
I looked at the output and ASP.NET is recognizing the client side function:
ASP.NET JavaScript output:
var ctl00_ctl00_content_content_CustomValidator2 = document.all ? document.all["ctl00_ctl00_content_content_CustomValidator2"] : document.getElementById("ctl00_ctl00_content_content_CustomValidator2");
ctl00_ctl00_content_content_CustomValidator2.controltovalidate = "ctl00_ctl00_content_content_TextBoxDTownCity";
ctl00_ctl00_content_content_CustomValidator2.errormessage = "Delivery Town or City required";
ctl00_ctl00_content_content_CustomValidator2.display = "Dynamic";
ctl00_ctl00_content_content_CustomValidator2.evaluationfunction = "CustomValidatorEvaluateIsValid";
ctl00_ctl00_content_content_CustomValidator2.clientvalidationfunction = "TextBoxDTownCityClient";
Rendered custom validator:
<span id="ctl00_ctl00_content_content_CustomValidator2" style="color:Red;display:none;">Delivery Town or City required</span>
Can any one shed some light as to why both client and server side validation would not be firing.
Edit: Typo I pasted in the wrong function, problem still the same
Just another update to the last comment: where by the TextBox cannot be empty. I tested this out and it is not true. On a blank page the CustomValidator fired my client side validation function fine without a value:
<asp:TextBox ID="TextBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="CustomValidator" ClientValidationFunction="TextBoxDAddress1Client"></asp:CustomValidator>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
Use this:
<asp:CustomValidator runat="server" id="vld" ValidateEmptyText="true"/>
To validate an empty field.
You don't need to add 2 validators !
Your CustomValidator will only fire when the TextBox isn't empty.
If you need to ensure that it's not empty then you'll need a RequiredFieldValidator too.
Note: If the input control is empty,
no validation functions are called and
validation succeeds. Use a
RequiredFieldValidator control to
require the user to enter data in the
input control.
EDIT:
If your CustomValidator specifies the ControlToValidate attribute (and your original example does) then your validation functions will only be called when the control isn't empty.
If you don't specify ControlToValidate then your validation functions will be called every time.
This opens up a second possible solution to the problem. Rather than using a separate RequiredFieldValidator, you could omit the ControlToValidate attribute from the CustomValidator and setup your validation functions to do something like this:
Client Side code (Javascript):
function TextBoxDCountyClient(sender, args) {
var v = document.getElementById('<%=TextBoxDTownCity.ClientID%>').value;
if (v == '') {
args.IsValid = false; // field is empty
}
else {
// do your other validation tests here...
}
}
Server side code (C#):
protected void TextBoxDTownCity_Validate(
object source, ServerValidateEventArgs args)
{
string v = TextBoxDTownCity.Text;
if (v == string.Empty)
{
args.IsValid = false; // field is empty
}
else
{
// do your other validation tests here...
}
}
Client-side validation was not being executed at all on my web form and I had no idea why. It turns out the problem was the name of the javascript function was the same as the server control ID.
So you can't do this...
<script>
function vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="vld" />
But this works:
<script>
function validate_vld(sender, args) { args.IsValid = true; }
</script>
<asp:CustomValidator runat="server" id="vld" ClientValidationFunction="validate_vld" />
I'm guessing it conflicts with internal .NET Javascript?
Also check that you are not using validation groups as that validation wouldnt fire if the validationgroup property was set and not explicitly called via
Page.Validate({Insert validation group name here});
Did you verify that the control causing the post back has CausesValidation set to tru and that it does not have a validation group assigned to it?
I'm not sure what else might cause this behavior.
Server-side validation won't fire if client-side validation is invalid, the postback is not send.
Don't you have some other validation that doesn't pass?
The client-side validation is not executed because you specified ClientValidationFunction="TextBoxDTownCityClient" and this will look for a function named TextBoxDTownCityClient as validation function, but the function name should be
TextBoxDAddress1Client
(as you wrote)
Thanks for that info on the ControlToValidate LukeH!
What I was trying to do in my code was to only ensure that some text field A has some text in the field when text field B has a particular value. Otherwise, A can be blank or whatever else. Getting rid of the ControlToValidate="A" in my mark up fixed the issue for me.
Cheers!

Categories