Validating User Input Using Regex within if Statement in asp.NET - javascript

I'm a complete beginner with C# and the .net framework, but have some experience with Python & scripting in a software-specific language I use at work. For my first ASP.NET project, I've taken a form that my director built and added validation so any input other than "420" will not pass front end, and automatically display a popup to try again before going on to the next field.
I would like to modify my working script to check the user input variable against a RegularExpression, and invalidate responses that are not Valid Visas, or Valid Mastercards, but have not had success in testing.
I would appreciate any guidance possible, and any suggestions on a good book or printable archive of LearningMaterial/tutorials on developing with asp.net and C# for beginners. As you can tell, I’m not there with the Syntax yet lol.
ORIGINAL CODE
<label>Credit Card Number<input type="text" size="24" name="rmwebsvc_pudf_CCNumber" class="required" style="width:300px;" onblur="cc_number_saved = this.value;
this.value = this.value.replace(/[^\d]/g, '');
if(this.value != ^(?:4[0-9]{12}(?:[0-9]{3})? # Visa
| (?:5[1-5][0-9]{2} ) {
alert('Sorry, that is not a valid Credit Card number - please try again!');
this.value = '';
}
" onfocus="if(this.value != cc_number_saved) this.value = cc_number_saved;" /></label>

I recommend you to use fluent validation. It has a good integration with asp. Net.
Here is the link https://fluentvalidation.net
After doing that you don't need to call the validation explicitly because it should be integrated into the MVC pipeline, which means that you get an invalid ModelState in case the validate finds an error.
They have built-in validators, but you can write your own. One of the built-in is a regular expression. Check it here https://fluentvalidation.net/built-in-validators.
The credit card is another built-in they have, if it is not implemented at this moment I think they are working on it now. Check here. https://github.com/JeremySkinner/FluentValidation/blob/master/src/FluentValidation/Validators/CreditCardValidator.cs
Sure there are other ways to validate the input, but also with this one, you can isolate your validation logic and reuse it in another project that has the same business rules or in another UI(web, desktop) that shares the same logic. Where it shines is on the testing.
Hope this helps

Related

How to use JsonSchema for real-time client-side validation?

I'm evaluating using JSON Schema for validating form data.
I can use it to validate my form data when you click submit using AJV and then check it again on the server using a PHP implementation of JSON Schema.
That part sounds great, but I'm trying to figure out how I would use it for real-time validations -- i.e., validation as you're filling out the form/typing.
Specifically, I can run the entire validator on every keystroke, but it seems expensive to validate the whole form when only one input has changed. In particular, any AJAX-based validations (such as a username uniqueness check) would fire too frequently.
Has anyone used JsonSchema for this purpose? Is it feasible? How would I fine-tune AJV or another JsonSchema implementation to only run the validators that are necessary on input?
Integrating this with the client will depend heavily on what you're using on the client side. I'm working on a project using this with dynamically created forms in Angular 2+ and AJV and it is working really well.
It will also depend on how much of JSON Schema you're using. For example, I want my forms to be able to use $data references so that validity of one input can depend on the value of other inputs. This basically means I have to validate on any change in the form since there's not an effective way to tell what value is the target of a $data reference.
Also, if there's any potential for your model data to change outside of the user interacting with the form (e.g., new data being pulled from the server from other users, etc.) it is much more resilient to validate the schema and model in its entirety.
In general even on my more complicated forms with up to 30-40 input values ajv takes less than 10ms to validate the entire form including a function of my own to match ajv's errors to my inputs for display. So I wouldn't worry about the performance hit.
Edit: As for the async validators adding a debounce of some sort will depend on what you're using client side, but shouldn't be too hard and AJV's documentation is really complete.
Edit: Here's the loop I have the errors go through to match them and clean them up a little (most of AJV's errors are user readable, but a few like pattern matching need some help rather than spitting out a regex at the user):
errs.forEach((err) => {
// Is this a value that is being matched to another input?
if (err.dataPath === dataPath && err.keyword === 'const' && err.schema.$data) {
return messages.push('Does not match')
}
// Don't show regex to people.
else if (err.dataPath === dataPath && err.keyword === 'pattern') {
return messages.push('Not valid format')
}
// Is the keyword 'required' and the parentPath is a match and the property is matched to err.params.missingProperty
else if (err.keyword === 'required' && err.dataPath === parentPath && err.params.missingProperty === propertyName) {
return messages.push('Required')
}
// Is the dataPath a match and no other special criteria apply
else if (err.dataPath === dataPath) {
// Cap first letter
return messages.push(err.message.charAt(0).toUpperCase() + err.message.slice(1))
}
})

Get credit card type for custom form using braintree

In my from card number field, on key up i want to show the card type with icon.
For that im using braintree.. see below code
braintree.setup(clientToken, "custom", {
id: "checkout",
onPaymentMethodReceived: function(obj){
console.log(obj.details.cardType);
}
});
With the above code im getting the credit card type on submit, how can i make it to happen on key up...
Thanks
Check out this.
Card types and their format is provided which wil make it easier for you to create regex.
Use the following tools to build and test regex.
https://regex101.com
http://regexr.com

Can I get robust XSS protection in CF11 that I can apply to an entire site without touching every query or input?

So I'm currently using CF11 and CFWheels 1.1, the "Global Script Protection"(GSP) server feature does an awful job of covering the XSS bases. I would like to extend it to block any and all tags/vectors for JS from being inserted into the database.
CF11 offers antiSamy protection via the getSafeHTML() function which applies a xml policy file specified in application.cfc but I would still need to modify every single varchar cfqueryparam in the application to use it right?
Is there a way to get CF11 to enable the antisamy features server or application wide in a similar way that the GSP feature works? What I mean by this is GSP automatically strips tags out of input submitted to the app without having to modify all the queries/form actions. I'd like a way to apply the antisamy policy file or getSafeHTML() in the same way.
Thanks!
Why would you have to apply it to every one? You would only need to do it for string (varchar) inputs and only when inserting. And even then, you wouldn't use it everywhere. For example, if you ask for my name and bio, there is no reason why you would want html, even "good" html, in my name. So I'm sure you already use something there to escape all html or simply remove it all. Only for a field like bio would you use getSafeHTML.
Validation is work. You (typically) don't want a "all at once" solution imo. Just bite the bullet and do it.
If you did want to do it, you can use onRequestStart to automatically process all keys in the form and url scope. This is written by memory so it may have typos, but here is an example:
function onRequestStart(string req) {
for(var key in form) { form[key] = getSafeHTML(form[key]); }
for(var key in url) { url[key] = getSafeHTML(url[key]); }
}
I agree with Ray, validation is work, and it is very important work. If you could have a server wide setting it would be way to generalized to fit all situations. When you do your own validation for specific fields you can really narrow down the attack surface. For example, assume you have a form with three fields; name, credit card number, social security number. With one server wide setting it would need to be general enough to allow all three types of input. With your own validation you can be very specific for each field and only allow a certain set of characters; name - only allows alpha characters and space, credit card number - only allows digits, space, dash and must conform to the mod rule, social security number - only allows digits and dash in 3-2-4 format. Nothing else is allowed.
That being said, I just wanted to point out that the "Global Script Protection" rules can be customized. That setting works by applying a regular expression that is defined in the cf_root/lib/neo-security.xml file in the server configuration, or the cf_root/WEB-INF/cfusion/lib/neo-security.xml file in the JEE configuration to the variable value. You can customize the patterns that ColdFusion replaces by modifying the regular expression in the CrossSiteScriptPatterns variable.
The default regular expression is defined as:
<var name='CrossSiteScriptPatterns'>
<struct type='coldfusion.server.ConfigMap'>
<var name='<\s*(object|embed|script|applet|meta)'>
<string><InvalidTag</string>
</var>
</struct>
</var>
Which means, by default, the Global Script Protection mechanism is only looking for strings containing <object or <embed or <script or <applet or <meta and replacing them with <InvalidTag. You can enhance that regular expression to look for more cases if you want.
See Protecting variables from cross-site scripting attacks section on this page
The solution as implemented for a cfwheels 1.1 app:
I used the slashdot file from https://code.google.com/p/owaspantisamy/downloads/list
This goes in application.cfc:
<cfcomponent output="false">
<cfset this.security.antisamypolicy="antisamy-slashdot-1.4.4.xml">
<cfinclude template="wheels/functions.cfm">
</cfcomponent>
This goes in the /ProjectRoot/events/onrequeststart.cfm file
function xssProtection(){
var CFversion = ListToArray(SERVER.ColdFusion.productversion);
if(CFversion[1]GTE 11){
for(var key in form) {
if(not IsJSON(form[key])){
form[key] = getSafeHTML(form[key]);
}
}
for(var key in url) {
if(not IsJSON(url[key])){
url[key] = getSafeHTML(url[key]);
}
}
}
}
xssProtection();

Two questions: should I do client-side or server-side in terms of validation? Also, how would I verify that no textbox is blank/invalid...

...with jquery/javascript? I want to check and make sure that a value has been entered and that it's a number.
First - Is it a best practice to do validation on the client-side, server-side, or both? Is this something that should be validated twice or is checking on the client-side enough?
Second - If client-side validation is the best way to go about this, how could I do this with javascript/jquery? I assume that for the button that's clicked, I would assign its onclientclick equal to a javascript function.
1) Validation should, at minumum be done on the server side. Both is even better.
2) If you wanted to do easy validation, you would simply attach to either a button click event, or better even, the form submit event.
$('form').submit(function()
{
// Do My Validation
// return false if invalid, true otherwise
});
You need to do both, and you should use jQuery Validate for the client-side.
Client side validation is purely for convenience of user and server, NOT for data sanitation. Consider the fact that you can open your dev tools and change the JS as you please on the fly - you could completely bypass client side validation. It is, however, good that it doesn't require you to load any more data and allows you to validate before navigating off.
Like the other answers say, using server-side and client-side together would be best. Client-side can always be passed by people knowing what they are doing. Even if someone just turns off Javascript all-together, client-side validation is worthless.
My recommendation is to set up everything on the server, then go back and fix it for the clients. Javascript and jQuery are the most common items used for validation. One of the things I use with Javascript is preventing any submit button until after everything checks out, for example:
document.getElementById("submitbutton").innerHTML = '<input type="submit" value="Log In" />';
Putting in that after everything checks out with the validation would place the input button in a div with the id of "submitbutton".
An example of some Javascript just to make sure there is input for a box would be this:
var textValue = document.getElementById("idOfTextBox").value;
if(textValue == null || textvalue == "")
{
document.getElementById("errordiv").innerHTML = "Please fill out a value for the text box";
}
If this is set for onKeyUp or onBlur for each text box, it can be pretty useful in making sure every box has its input.
There are few client side Validations here
First - Is it a best practice to do validation on the client-side,
server-side, or both? Is this something that should be validated twice
or is checking on the client-side enough?
Client Side - It is always good. provided that the javaScript is not blocked. Client side validation speed up the process. Reduces the execution time.
Server Side - It's always bother-less. Just need to compromise with the performance.
Both Side - I can go for RegularExpressionValidator and Server side validation.
Second - If client-side validation is the best way to go about this,
how could I do this with javascript/jquery? I assume that for the
button that's clicked, I would assign its onclientclick equal to a
javascript function.
In this Example I will explain how we can prevent the user to type non
alphabets in numeric textbox.
Mark Up
<asp:TextBox ID="FirstName" runat="server" AutoComplete="Off"
onKeyup="return AlphaNumeric(this);" onchange="return AlphaNumeric(this);"></asp:TextBox>
Sample JavaScript code
<script language="javascript" type="text/javascript">
function AlphaNumeric(controlID) {
document.getElementById(controlID.id).value =
NumericValidation(document.getElementById(controlID.id).value);
return true;
}
function NumericValidation(val) {
var Reg = new RegExp('[^a-zA-Z]+');
var Result = val.match(Reg);
if (Result) {
val = val.replace(Reg, '');
return val;
}
else
return val;
}
</script>

Search for embedded email and phone numbers

I need to use a javascript form validation routine to scan various input text fields for embedded phone numbers and email addresses. This is for a classifieds system that is free to post but 'pay to connect' with buyers, so the intent is to prevent (as much as possible) the ability for users (those posting the ad) from simply embedding their phone and/or email contact information to bypass the system.
I've been googling for awhile now, and RegEx is not my strong suit, so I'm having a bit of a hard time finding a good snippet of code to help. All I want to do is get a pass/fail for a text field (pass if it does not appear to have embedded email and/or phone numbers, and fail if it does)
Does anyone already have a good javascript solution for this?
Try this:
var text = textArea.value;
if (text.search(/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,6}$/))
...;//Contains email
if (text.search(/^[+]?(?!0{5})(\d{5})(?!-?0{4})(-?\d{4})?$/))
...;//Contains phone
Thanks to all for the input. Here is the version I ended up with, hope it helps someone else. Note: I removed the actual 'bad' words for this posting so that it would pass this site's filters. You can replace 'badword1', 'badword2', etc. with actual 'bad' words (you know, like nukular, calender, ekcetera):
function isAllowed(varField) {
var msg = '';
var pass = true;
var regex0=/\b(#|www|WWW|http|hotmail|gmail|badword1|badword2|badword3)\b/i;
if (regex0.test(varField))
{
msg += "Text appears to have disallowed words (e.g. profanity, email, web address, # symbol, etc.)\n";
pass = false;
}
var regex1=/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/i;
if (regex1.test(varField))
{
msg += "Text appears to have email address in it (not allowed\n";
pass = false;
}
var regex2=/\b\(?\d{3}\)?[-\s.]?\d{3}[-\s.]\d{4}\b/i;
if (regex2.test(varField))
{
msg += "Text appears to have a phone number in it (not allowed)\n";
pass = false;
}
if (msg!='')
{
alert(msg);
}
return pass;
}
This will find email addresses: \b[A-Z0-9._%+-]+#[A-Z0-9.-]+.[A-Z]{2,4}\b
and this will find phone numbers: \b(()?\d{2,3}(?(1)))(?:-?\d{3}-?\d{4}|\d{11})\b
You'll be able to get some, but don't expect to get most (especially if people are aware of the requirement, or get more than one chance to fill the form).
People are already really good at circumventing bot detection of email addresses by doing things like "myaddresses at hotmail dot com", and there are a million variations of this. Also, Phone numbers vary by region.
You don't say what server side technology you're using, but it might be preferable to do this type of processing on the server. I always favor server side in my own work (ASP.NET), because the flexibility and power of an object oriented server side framework will trump that of JavaScript just about every time. This case is no exception, as it appears that JavaScript regular expression support is lacking several key features.
Regardless of whether you choose to go server side or client side, I've found that writing RegEx code is much simplified when using a tool such as Espresso. If you're running on a Mac, consider Reggy. These tools usually come with several "stock" RegEx expressions for various common queries (i.e. phone numbers, email etc) that usually work with minimal modification.

Categories

Resources