简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM