Validate a string based on certain Format - c#

I need to validate a input string based on certain formats i.e
Proj-######## (4 alphabets, 1 Dash and 8 numbers)
OP###### (2 characters, 6 numbers)
Can someone please help me on this?
I tried with the below approach it's working for 1 dash and 8 numbers. but am not geeting how to add code into regerx for allow only 4 charactes.
private static readonly Regex boxNumberRegex = new Regex(#"^\d-\d{8}$");
public static bool VerifyBoxNumber (string boxNumber)
{
return boxNumberRegex.IsMatch(boxNumber);
}

Try this.
\b[a-zA-Z]{4}-\d{6}\b - is for Proj-########
\b[a-zA-Z]{2}\d{6}\b - is for OP######
If you want to learn bulding regular expressions, have a look at this article. Worth reading it.
http://www.codeproject.com/Articles/9099/The-Minute-Regex-Tutorial

Related

How can I best limit the decimal places to 5 or shorten the longer ones?

I have a file with various characters and either words as well as numbers. These numbers can be integers like a 1 or 12 (as an example) or they have a comma and countless digits after the comma.
for example:
",{"n":"Box","p":[-4.0,4.0,0.0],"r":[270.0,0.0,0.0],"s":[1.0,1.000006,1.000006],"c":[0.448529363,0.4280135,0.412251264],"m":"wood_14"}"
The file is read with File.ReadAllText and then passed to NewtonsoftJson via JsonProperty accordingly
for example:
[JsonProperty("s")]
public double[] Scale
{
get;
set;
}
For example, with Scale, I want to limit the decimal places to a maximum of 5 digits.
Is this possible and if so, how?
I have been trying for days with different things, but nothing has worked yet.
My idea was to intervene in the string I build first before passing that to Json there. But unfortunately this does not work. I tried it with regular expression like Notepadd++ makes for example.
(edit)
I don't know if you want it to serialize or deserialize. So I made code for both cases. You have to leave one variant or another
public class a
{
private double[] val;
[JsonProperty("s")]
public double[] Scale
{
get { return val;
// or
val?.Select(v => Math.Round(v, 5)).ToArray(); }
set {
val=value;
//or
val = value?.Select(v => Math.Round(v, 5)).ToArray();
}
}
}
if you want it in many properties you can make it as a function
double.ToString() will do it.
const double d = 0.123456789;
string s = d.ToString("G5");
Console.WriteLine(s);
That outputs 0.12346, showing that it rounds the 5 to 6.
Documentation for Double.ToString shows much more detailed examples of how to format numbers.
The number format (i.e. decimal separator) is culture-specific. If you want to use the current culture, then the above will work. If you always want a comma as the decimal separator, you'll have to call the overload that accepts an IFormatProvider for the specific culture.

How to validate comma-separated string using Regex [duplicate]

This question already has answers here:
Regular expression help - comma delimited string
(7 answers)
Regular expression to find and remove duplicate words
(9 answers)
Closed 2 years ago.
I need to validate my c# model class.
[Required(ErrorMessage = "Comma Separated String Required")]
[RegularExpression(#"", ErrorMessage = "Invalid Comma Separated String.")]
[RegularExpression(#"", ErrorMessage = "Duplicate Code.")]
public string CommaSeparatedString { get; set; }
I just tried the following regex, but it is not working for me.
((\s+)??(\d[a-z]|[a-z]\d|[a-z]),?)+?$
In my case, CommaSeparatedString can be:
ASAEW1,ASAEW2,ASA,S4,ASAEW5,ASAEW6,ASAEW7 - Valid
ASAEW1,ASAEW2,ASA,S4,ASAEW5,ASAEW6,ASAEW7,ASAEW6 - Invalid - Duplicate ASAEW6
ASAEW1,ASAEW2,ASA,S4,ASAEW5,ASAEW6,ASAEW7, - Invalid - Comma at end
ASAEW1,ASAEW2,,ASA,S4,ASAEW5,ASAEW6,ASAEW7 - Invalid - No value between 2,3 comma
The above requirement should happen. Is there any possible way to check duplicates in comma-separated String? I need to show 'Duplicates code' error message if CommaSeparatedString consists of duplicates. How can I do this?
I'm not a regex magician, but puzzled together something that might work for you here:
^((([A-Z]+\d*)(?!.*,\3\b)),)*[A-Z]+\d*$
So to visualize this:
In steps:
^((( - Start string ancor followed by three capture groups
[A-Z]+\d* - Third capture group must exist out of capitals (at least one) followed by as many digits as possible
(?!.*,\3\b) - Negative lookahead to make sure that previously found pattern will not have a duplicate further down the line.
),)* - Closing group 2 followed by a comma and closing group 1 which then must occur * as many times as possible
[A-Z]+\d* - The last bit is repeating the same pattern we were looking for in group 3
$ - End string ancor
I'm not the best at explaining either but I hope it's clear enough and working (hoping backreferences are allowed within c# as I have no experience in that) =)
You can take a look at custom validations for your model, using either the ASP.Net (Core?) framework or the FluentValidation Nuget package.
For a solution depending only on the framework, I write a sample that might work for you or at least get you started:
public class MyModel : IValidatableObject
{
public string CommaSeparatedString { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (CommaSeparatedString.EndsWith(","))
{
yield return new ValidationResult("Invalid Comma Separated String - Comma at end");
}
var splitCodes = CommaSeparatedString.Split(",");
var setOfCodes = new HashSet<string>();
foreach (var code in splitCodes)
{
if (code.Trim() == String.Empty)
{
yield return new ValidationResult("Invalid Comma Separated String - Missing Code");
continue;
}
var added = setOfCodes.Add(code);
if (!added) yield return new ValidationResult($"Duplicate Code: {code}");
}
}
}

Issue with Validating Phone number on user input,Int to large c#

Overview of Project:
I am creating a multi form application, which consist of two forms and one parent class. Both Forms have a series of validation functions, such as isLetter() isNumber() and isValidEmail(). My Issue comes when using the isNumber() Function.
public static bool numValidation(string strNum)
{
if (!string.IsNullOrWhiteSpace(strNum))
{
int temp;
if (int.TryParse(strNum, out temp))
{
Console.WriteLine("Phone Number is a valid input: " + temp);
return true;
}
else
{ Console.WriteLine(temp + "Is not Valid input!!"); }
}
return false;
}
At first glance it works fine but once I tried to break it, I realised that when an actual phone number is entered I get an error saying that the number is too high. Any ideas how to get round this constraint ? as the only reason I need this validation is for phone numbers, Fax etc. I simply need this function to accept very large numbers such as phone numbers
I suggest that you use a regular expresion to validate the input in your case
public static bool numValidation(string strNum)
{
Regex regex = new Regex(#"^[0-9]+$");
return (regex.IsMatch(strNum)) ;
}
Parsing a string and not using that value is not really needed.
For more details checkout this answers - Regex for numbers only
From Mauricio Gracia Gutierrez answer
I suggest that you use a regular expresion to validate the
input in your case
public static bool numValidation(string strNum) {
Regex regex = new Regex(#"^[0-9]+$");
return (regex.IsMatch(strNum)) ; } Parsing a string and not using that value is not really needed.
For more details checkout this answers - Regex for numbers only
You could enhance the expression to check the length of the number:
Between 5 and 10 digits:
Regex regex = new Regex(#"^[\d]{5,10}+$");
Max 10 digits:
Regex regex = new Regex(#"^[\d]{10}+$");
At least 5 digits:
Regex regex = new Regex(#"^[\d]{5,}+$");

Format String to Match Specific Pattern

I am trying to figure out how to format a string to a specific pattern.
When a user is entering their employee id number, they often get confused on what is expected from them. Because they are often told that their employee id is either a 5 digit or 4 digit number depending on when they were hired.
For example, my employee id number is E004033 but for most of our systems, I just have to enter 4033 and the system will find me.
We are trying to add this to one of our custom pages. Basically what I want to do is format a string to always look like E0XXXXX
So if they enter 4033 the script will convert it to E004033, if they enter something like 0851 it will convert it to E000851 or if they enter 11027 it will convert it to E011027
Is there a way basically add padding zeros and a leading E if they are missing from the users input?
You can simply:
var formattedId = "E" + id.PadLeft(6, '0');
To remove an existing leading E(s)
var text = "E" + val.TrimStart(new[] {'E'}).PadLeft(6, '0');
Make sure the user's input is an integer, then format to 6 spaces using String.Format.
int parsedId;
bool ok = int.TryParse(id, out parsedId);
if (ok)
{
return String.Format("E{0:000000}", parsedId);
}

Validate that the phone number only contains only numbers [duplicate]

This question already has answers here:
How to validate phone numbers using regex
(43 answers)
Identify if a string is a number
(26 answers)
Closed 8 years ago.
I need to do a phone number validation that the tel# contains only:
numbers 0-9
left and right parenthesis
hyphen
blank space
in c#
this is my code for now:
//ValidatePhoneNumber
public static string ValidatePhoneNumber(string v_strPhoneNumber)
{
const string strPHONE_NUMBER_BLANK =
"Phone Number cannot be blank";
const string strPHONE_NUMBER_TOO_LONG =
"Phone Number cannot be longer than 24 characters";
if (v_strPhoneNumber.Trim().Length == 0)
return strPHONE_NUMBER_BLANK;
if (v_strPhoneNumber.Trim().Length > 24)
return trPHONE_NUMBER_TOO_LONG;
return String.Empty;
}//end ValidatePhoneNumber
I need to add that validation into that code, I am a beginer so the easiest way possible would be great. If you can give me the answer please if you could at least point me in the right direction, Thanks!
This the RegEx that I use for telephone number validation
^((| |)\d{3}()| |)(-| )\d{3}-\d{4}$
You just need to adjust it to your needs.

Categories