The last line of defense is the server side - that should be mandatory.
Client Side validation, in my opinion, is purely for the benefit of the user in that they get instant feedback on how to correct their input, before it's even a problem...other obvious benefit is that reduces resource requests on the server as it avoids having to post back to the server every time you need to validate some input.
In the event that the Client Side validation does not perform its duties, unless you validate on the server as well, you've left your site wide open for attack - so you should really have both.
If you were to only validate *some* things client side and others server side (eg REGEX validation on email syntactically client side and then server side, validate that that particular email isn't already registered on the site)
Server Side
This appears to be a popular routine around the net:
public static bool isEmail(string inputEmail) { inputEmail = NulltoString(inputEmail); string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" + @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"; Regex re = new Regex(strRegex); if (re.IsMatch(inputEmail)) return (true); else return (false); }
Shawpnendu has another method which appears a little cleaner. He creates static Validation class which encapsulates commonly required validation routines. ValidateEmail being one of them. I prefer to call mine something more like "IsEmailValid". Using Shawpnendu's example, my derivation is:
public static class Validation { public const string EmailStandard = @"^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$"; public static bool IsEmailValid(string emailID) { if (emailID != null) return System.Text.RegularExpressions.Regex.IsMatch(emailID, EmailStandard); else return false; } } // USAGE: ELSEWHERE IN CODE-BEHIND etc. if (Validation.IsEmailValid(txtEmail.Text)) { //Valid Email } else { //Invalid Email //Notify user return; }
Client Side
Here is an example of client side validation which takes advantage of the RegularExpressionValidator control provided as of ASP.Net 1.1:
<div class="divContainerCell"> <asp:textbox id="txtEmail" runat="server"></asp:textbox> <asp:requiredfieldvalidator
controltovalidate="txtEmail"
errormessage="Please provide your email address!"
forecolor="Red"
id="valRequiredEmail"
runat="server">*</asp:requiredfieldvalidator>
<asp:regularexpressionvalidator
controltovalidate="txtEmail"
errormessage="This does not appear to be a valid email address!"
forecolor="Red" id="RegularExpressionValidator2"
runat="server"
validationexpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
>*</asp:regularexpressionvalidator> </div>
No comments:
Post a Comment