Are you looking for customized advices? Click here to contact the expert!
by
0
8
3,167
2
Top 1% !
Popular
Famous
Tagged
Easy-to-find
Specified
Refined
OpenSource
Popularity: 3971st place
Created
Modified Jan 31, 2014

Published on:

.NETFramework4.0
Architecturex86_64
Extension.cs
InputName0candidateName
InputName1minimumLen
InputName2checkOnlyLen
InputName3maxLen
InputType0string
InputType1int
InputType2bool
InputType3int
LanguageCSharp
LicenseMIT_X11
MethodNameNameIsValid
OSWindows
OutputTypebool

C#: How to dinamically check a string and its length using a Regex

Thsi method creates a Regex by replacing a placeholder as minimum and maximum length (e.g. in case of username and / or password verifiers...). 
It can be extended also to apply different Regex with respect to some particular business logic.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/25655/C---How-to-dinamically-check-a-string-an?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
static private string s_nameRegEx = @"^[_a-zA-Z][_a-zA-Z0-9-. ]{ç,§}$"; //'ç' is a placeholder for actual minimum length, '§' is a placeholder for actual maximum length public static bool NameIsValid(string candidateName, int minimumLen, bool checkOnlyLen, int maxLen = int.MaxValue) { if (candidateName == null) return (minimumLen == 0); //return false if there's a minimum len string trimmedName = candidateName.Trim(); if ((trimmedName.Length < minimumLen) || (trimmedName.Length > maxLen)) return false; if (checkOnlyLen) return true; Regex nameExpr = new Regex(s_nameRegEx.Replace("ç", (minimumLen - 1) + "").Replace("§", (maxLen - 1) + "")); return nameExpr.IsMatch(trimmedName); }
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus