ASP.NET C# client-side & server-side validation with regular expressions - c#

I have a pretty straightforward aspx form that collects name, address, email etc and I'm trying to do server-side validation using asp controls. It's working (I think?) and I know I need to do it server-side, but I'm not sure exactly where to put the regex for the actual requirements for each field.
Here's one of my fields as an example:
<div class="form-group">
<asp:Label runat="server" AssociatedControlID="FirstName" CssClass="col-md-2 control-label">* First Name</asp:Label>
<div class="col-md-3">
<asp:TextBox runat="server" ID="FirstName" CssClass="form-control" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="FirstName"
CssClass="text-danger" ErrorMessage="First Name field is required." Display="Dynamic" />
</div>
</div>
I've been using an asp:RequiredFieldValidator and the client-side validation part is working perfectly. The form knows when the user has or hasn't entered something into my required fields and notifies them accordingly before sending anything to the server. I've tested it by putting a label on my page called "valid" and then putting this into my submit button click event:
if(Page.IsValid)
{
valid.Text = "it's working";
}
And when I fill out the required fields my label does indeed appear and say it's working. However, the asp:RequiredFieldValidator, by definition, only indicates whether my required fields have a value of some kind. It does nothing to check the formatting of what the user entered.
I do need to make certain fields required and I like how the client-side validation part is working. But I also need to do server-side validation and use regex somewhere in the mix to make sure they actually entered an e-mail address in the e-mail field and actually put numbers in the zip code field etc.
I'm fairly new to ASP.NET and it's starting to feel like I'm fighting it. I don't want to fight it. I want to use the available tools to do pretty standard server-side validation, I'm just not exactly sure where to put the regex.
Can anyone help?
Thanks

Web Forms validators add client and server side code automatically to cover both bases. In the case of your RequiredFieldValidator, it simply checks the value is present on the client and if you also call "Page.IsValid" when Page_Load is fired it will do so on the server end.
What you are after is the "RegularExpressionValidator". You can use one or both on the page depending on what you are trying to achieve.
Here's a good example: https://msdn.microsoft.com/en-us/library/ff650303.aspx

You can write your own validator, client and server side. Check out
CustomValidator
Example:
<asp:CustomValidator runat="server" id="CustomValidator" ValidateEmptyText="false" OnServerValidate="customValidation_event" ClientValidationFunction="customValidation_client" />
And add javascript function and validation method in your code-behind.

Related

ASP.net - How to reference a text box in the code behind?

This is highly likely to be a stupid question, so my apologies. But I can't seem to find an answer anywhere. I am brand new to ASP.net and I'm using C# for the code behind (I have experience with C# from a WinForms project I did, also in Visual Studio)
I have a page, a register for an account page, on the website and I want to be able to access the TextBox that contains email and password etc. I thought it would be something like textboxname.getText() or similar to get what the user has typed into that box when they press submit (clicking submit is my Event) but I don't now how to make it recognize that textboxname is the ID.
For example:
<input type="email" class="form-control" placeholder="Enter Email" id="email"/>
My email TextBox has an ID of 'email'. In code, if I try to type email.getText(), it does not recognize that email refers to that TextBox. If I could even get it to recognize the ID, I could figure out the rest from there.
Thank you for listening to my excessive beginner ranting! If any extra details are necessary I'll add them, just ask.
Resolved! - For some reason it did not generate a designer for my pages when i created the web forms, so i regenerated the design.cs and it is working! :D Thanks for help anyway!
Be sure your markup is correct on front end - even if you are a space off between quotes it can mess things up.
<asp:TextBox id="email" runat="server" Text="Email" />
email.Text = "your text here";
You should use email.Text; (since it's a property, no a method) instead of email.getText(). Also make sure your control has runat property equals to "server" on HTML.
On your page
you have to declare a form with a submit button and within this form you can have your textbox.
<form id="myForm" runat="server">
<asp:TextBox id="TB_Email" placeholder="Enter Email" runat="server"></asp:TextBox>
<asp:Button ID="Btn_Submit" runat="server" Text="Submit" OnClick="Btn_Submit_Click" />
</form>
Code behind
protected void Btn_Submit_Click(object sender, EventArgs e)
{
// here you can access the value of your email-textbox
String email = TB_Email.Text;
}
Use:
<input type="email" class="form-control" placeholder="Enter Email" id="email" runat="server"/>
or alternatively,
<asp:TextBox id="email" runat="server"/> /*Add any other attributes you need*/
In the code behind:
email.Text="your text here";
Without runat="server" attribute, your control is just a HTML control and hence you cannot access it from the server side code(code behind).

ASP.Net form validation - bypass client side only on button click

I have a form with a bunch of fields that I am using RequiredFieldValidator, RegularExpressionValidator, and CustomValidator.
I want my form to perform client side checks when tabbing between fields (it currently does this), but I want to force a server side submit when the asp:button is clicked. Right now, if a form field is determined invalid on the client side, the submit button doesn't do anything. I want it to submit the page and perform the server side check.
The reason I want this to happen is because I want the page to go back to the top and display all possible issues and make it obvious to the user that there was a problem. Currently if they didn't see the client side error message, they may just click submit, see nothing happen, and end up confused.
Example field on aspx Page:
<asp:TextBox MaxLength="30" ID="LNom" runat="server" /><asp:RequiredFieldValidator ID="reqLNom" runat="server" ErrorMessage="Last Name Required" ControlToValidate="LNom" /><asp:CustomValidator ID="valLNom" runat="server" ErrorMessage="Please enter a valid last name (less than 30 characters in length)." ControlToValidate="LNom" OnServerValidate="ValidationLastName" />
<asp:Button ID="Submit" Text="Submit" runat="server" onclick="Submit_Click" />
Submit button Code Behind:
protected void Submit_Click(object sender, EventArgs e)
{
Page.Validate();
if (Page.IsValid)
{
// Do stuff
}
}
Obviously there is a bit more to this, but you get the idea.
Try asp.net ValidationSummary. See http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.validationsummary(v=vs.110).aspx
It does exactly how you want it. It can be a pop up or inline notification that tells the user what s/he needs to fix.
If you add 'CausesValidation="False"' to your asp:button declaration. This will cause the postback to happen regardless of the outcome of client side validation
You can do this client side, no need for a post back. Look into the ValidationSummary control:
http://www.w3schools.com/aspnet/control_validationsummary.asp

Show confirmation textbox after entry with JavaScript

Before we begin, I would like to convey that I have limited to no knowledge on the JavaScript language. The only things I've used is JQueryUI - and even that is copy paste.
Currently, I have a user registration page, with all the standard TextBox inputs. I would like to, however, slide down a secondary 'Confirm email' and 'confirm password' whenever a user enters text into the original text box.
I understand the community likes to help those who can prove they helped themselves, but the only thing I currently have to show is me trying to lookup solutions for this and failing.
Could someone please show me a way to do this?
Edit: Code of the password box
<div class="ctrlHolder">
<asp:Label ID="Label9" runat="server" Font-Bold="True" Text="Password"></asp:Label>
<asp:Label ID="Label11" runat="server" CssClass="styleLabelWatermarkWashout" Text="**********"></asp:Label>
<br />
<%--data-default-value="Placeholder text"--%>
<asp:TextBox ID="txtRegisterPassword" runat="server" CssClass="textInput styleTextBoxCenter required"
TextMode="Password" MaxLength="20"></asp:TextBox>
</div>
So, assuming you can create markup similar to this:
<div class="ctrlHolder">
<asp:Label ID="PasswordLabel" runat="server" Font-Bold="True" Text="Password"></asp:Label>
<asp:Label ID="Label11" runat="server" CssClass="styleLabelWatermarkWashout" Text="**********"></asp:Label>
<br />
<%--data-default-value="Placeholder text"--%>
<asp:TextBox ID="txtRegisterPassword" runat="server" CssClass="textInput styleTextBoxCenter required" TextMode="Password" MaxLength="20"></asp:TextBox>
</div>
<div id="confirm-password-box" class="ctrlHolder">
<asp:Label ID="ConfirmPasswordLabel" runat="server" Font-Bold="True" Text="Confirm Password"></asp:Label>
<asp:Label ID="Label12" runat="server" CssClass="styleLabelWatermarkWashout" Text="**********"></asp:Label>
<br />
<%--data-default-value="Placeholder text"--%>
<asp:TextBox ID="txtConfirmRegisterPassword" runat="server" CssClass="textInput styleTextBoxCenter required" TextMode="Password" MaxLength="20"></asp:TextBox>
</div>
You'd want to add some CSS rules to make #confirm-password-box hidden by default. Then, add this script code somewhere on the page (preferably as close to closing </body> tag as possible):
<script>
$(function(){
$('#<%: txtRegisterPassword.ClientID %>').on('blur', function(event){
$('#confirm-password-box').slideToggle('slow');
});
});
</script>
The blur event occurs when the control loses focus. You don't really want to listen for keyup, since that would require this code being called every time a user entered a character into the password box...
Note that this particular chunk of jQuery code requires jQuery 1.7 or higher, so use NuGet to update your script reference (if you're not using anything else that requires an older version of jQuery).
I would add a reference to jquery to the page you are working on.
Then make a new script (on the page or in a separate .js file) which attaches a new function to the onkeyup event for the textboxes. Something like this.
$(document).ready(function()
{
$('mytextbox').bind('keyup', function() {
$('myCOnfirmationTextbox').slideDown();
};
});
This will attach this function to all elements corresponding to the "mytextbox" class or ID. So if you have an input <input type="text" id="email" class="emailInput"/> then you would use $('#email') to bind the event to this particular element. Or you use $('.Emailinput') to bind to all input elements for emails.
By the way, I haven't tested the code, but this or something very similar should work.
If you use a separate .js file, then don't forget to reference it in your page as well.
You can use innerHTML to have a new textbox beneath the email textbox once that box is filled. I could give you the code if you can post the code over here
Replace the controls ids in this answer as per your html.
You can show the confirm controls in the following way.
$('#password').onfocusout(function() {
// This will show once you complete entering Email and Password.
$('#confirmEmail').attr('display', 'inline');
$('#confirmPassword').attr('display', 'inline');
});
Let me tell how you can achieve confirm Email. Same thing can be used to achieve confirm password.
When you focus out of confirm email textbox compare the emails entered by the user in Email and Confirm Email textboxex.
This can be done in following way
$('#confirmEmail').onfocusout(function() {
if($('#confirmEmail').val() == $('#Email').val())
{
// Emails entered are same
}
else
{
alert('Emails entered are not matching. Please reenter emails.');
}
});
Similarly you can check for confirm password.

Can't pass 'complex objects' as parameters in Design view

I've created my own Validation controllers, to work with my own User Controls.
My Problem :
the classic validators accept parameters in 'design view', e.g.
<asp:RequiredFieldValidator ControlToValidate="txtFirstname" runat="server" />
and I'd like to do the same in my controls, but it appears when I pass 'ControlToValidate' a control ID, I get this error :
Cannot create an object of type 'System.Web.UI.WebControls.WebControl'
from its string representation 'txtFirstname' for the
'ControlToValidate' property.
What 'pattern' do I need to implement to ensure I can make the most of my 'ascx' page instead of having to hook up everything in my 'ascx.cs' code-behind page.
p.s. I'm calling the 'tags' I create on the 'ascx' page 'design view', but I think that is probably the wrong term, which I suspect is half the reason I cant find anythign on google for this.
Your code simply should look something like this (all in the .ascx):
<asp:TextBox id="txtFirstName"
Text="Enter a value"
runat="server"/>
<asp:RequiredFieldValidator id="RequiredFieldValidator1"
ControlToValidate="txtFirstName"
Text="Required Field!"
runat="server"/>
I'm guessing that you're not placing the RequiredFieldValidator in the same scope - causing this problem.

How to get javascript confirm box after validating the form data in asp.net?

I am facing a problem in my asp.net web application that i need to display a java script confirmation box on click of Update button and this as per requirements given to me.
Currently I am using onclient click
<asp:Button ID="btnCustomerUpdate" runat="server" CssClass="applybuttonstyle"
Text="Update" onclick="btnCustomerUpdate_Click"
OnClientClick="return confirm('Do you really want to update?');"/>
It's working fine but the problem is i also applied some validation controls on my form fields so if a user leave any field blank and click update button then it shows javascript confirm box and the validation message below that form field.
And it is not desired behavior it should not show the confirmation box until unless all validation are passed.
I hope this is due to because i am using this on client click so please tell me a better solution for that.
Thanks in advance.
you can use Page_ClientValidate in your own confirm function to decide whether to display the confirmation dialog.
Something like:
function validateAndConfirm(message){
var validated = Page_ClientValidate('group1');
if (validated){
return confirm(message);
}
}
And on the server you will have something like:
<asp:textbox id="TextBox1" runat="server"/>
<asp:requiredfieldvalidator ValidationGroup="group1"
ErrorText="Need to Fill in Value!"
ControlToValidate="TextBox1"
runat="server"/>
<asp:textbox id="TextBox2" runat="server"/>
<asp:requiredfieldvalidator ValidationGroup="group1"
ErrorText="Need to Fill in Value!"
ControlToValidate="TextBox2"
runat="server"/>
And your button code will change to:
<asp:Button ID="btnCustomerUpdate" runat="server" CssClass="applybuttonstyle"
Text="Update" onclick="btnCustomerUpdate_Click" ValidationGroup="group1"
OnClientClick="return validateAndConfirm('Do you really want to update?');"/>
Obviously, I cannot test this, but you get the idea.
If you will be using Page_ClientValidate you might find this SO question useful.
You can call the Page_ClientValidate method to ensure the page is valid before asking the user:
if (typeof(Page_ClientValidate) == 'function' && Page_ClientValidate() == false) {
return false;
} else {
return confirm('Do you really want to update?');
}
You should atleast apply validation on client side first and than open a confirmation dialog,
while on server, you have to use server side validation first too in case if user has disabled javascript, and than update the record.
You can also use AJAX to update record, so if a validation message occurs, shows error message and if the validation passed, than you can alert the user but the only disadvantage of using that is you have to re-post the data again. To mitigate this problem you either have to save in temporary table, until user gave confirmation and than delete it from temporary table but obviously it takes a lot of work.

Categories

Resources