To me regular expression validation seems straight forward and meaningfull rather than validating everything with asp.net validation controls. I am learning asp.net and do not want to memorize all asp.net validation controls, when any form input can be simply validate开发者_StackOverflow社区d with reqular expression. Am I thinking right or should I use validation controls?
Example:`RequiredFieldValidator vs Regex Solution C# if(TextBox1.Text == ""){ Label1.text = "Name Field is required, Please try again"; return; } CompareValidator vs Regex Solution if(Regex.IsMatch(TextBox1.Text, @"^[0-9]")){ if(Convert.ToInt32(TextBox1.Text) > 18){ output.InnerHtml = @"some code
"; } else{ Label1.Text = "You should be old enough to express out your political views "; return; } } else{ Label1.Text = "You should be old enough to express out your political views"; return; } }
`
Thinking would not be better to do everything in C#, rather than remembring all those validation controls
The major advantage to the validation controls is that in most cases they will output JavaScript validation for the client side that matches the server-side validation. This can reduce round trips to the server which is always a benefit. However, if you're good with JavaScript, you can probably code the client side piece more efficiently than the control would output anyway.
One other thing to consider, when using the control you can turn the validation on/off on both client and server using one flag on the control, if using your own code, you have to handle those separately.
You are right, regular expression validator can replace a lot of other validators, provided you can write a validation expression that works well on client and server side.
You can do a lot of validation work in regular expressions, but there are some areas where regexes are not ideal:
date validation: Either you get a terribly unwieldy regex, or you'll miss lots of plausible but illegal dates (like Feb 29, 2000).
email validation. Same thing here - you either reject some valid addresses, or you allow invalid addresses (and in either case, you'll allow addresses that are syntactically OK but don't correspond to an actual mailbox).
number validation in general - regular expressions are good for matching textual data. Using them to validate numbers is cumbersome and error-prone. Have you thought of exponential notation, locale-dependent decimal separators, thousands separators, leading zeroes, etc...?
Apart from that, the JavaScript regex engine has some limitations (e. g., lack of lookbehind assertions) that you need to know about when trying to write regexes that have to work both on the client and the server side.
And finally, do you realize that there's an error in your example regex? Maybe using a validator is safer unless you really know how to build a regex that does exactly what you intend it to do...
精彩评论