I have strange validation error
public long mobile { get; set; }
[RegularExpression(#"^([09]{2}[0-9]{8})$", ErrorMessage = "mobile number is not correct")]
if the user entered 094532415678 it is correct but validation error appears due to the dynamic removal of leading zeroes in asp c# , model will receive the above number as 94532415678 and wont be saved to database throwing error for mobile validation
I have tried to save it to string and add the leading zero to mobile and save it but still when the string gets converted to "long" directly it removes the leading zero , any solution for this problem
Store telephone numbers (and simular information) as a string. Leading 0's are removed when you save phonenumbers as a number (long).
try
[RegularExpression(#"^([09]{2}[0-9]{8})$", ErrorMessage = "mobile number is not correct")]
public string mobile { get; set; }
Related
I have a list of raw log data retrieved from Covalent (https://api.covalenthq.com/v1/137/events/topics/). I know what the event this log corresponds to, but how do I decode it into this event?
It looks like "0x000000000000000000000000000000000000000000000000000000000000002d00000000000000000000000097922d241bd4e4ef4bb0e13693284H8ea75a6c52"
The event is something like
[Event("TokenFound")]
public class TokenFoundEventDTO : IEventDTO
{
[Parameter("uint256", "tokenId", 1, false )]
public BigInteger TokenId { get; set; }
[Parameter("address", "buyer", 2, false )]
public string? Buyer { get; set; }
}
I expected Nethereum to provide something where I can translate that raw log data into an event like this but I cannot find anything like that. Could anyone help guide me to the right thing?
Thanks!
The token id seems to be a uint with 256 bits. That's 32 bytes which make up 64 characters in the hex string. If you trim the starting 0x and split the remainder in the middle you are left with two 64 character strings.
000000000000000000000000000000000000000000000000000000000000002d
00000000000000000000000097922d241bd4e4ef4bb0e13693284H8ea75a6c52
The first one (ending with "2d") should be parsed as a BigInteger (prepend the 0x again before that) and the second one seems to be the buyer address (maybe strip the leading zeros).
I need a regex which allows only 4 digits and those four can contain 0 at any position.
Below is my code:
View :
<label asp-for="UserId"></label><br />
<input asp-for="UserId" class="form-control" maxlength="4" />
<span asp-validation-for="UserId" class="text-danger"></span>
Model :
[RegularExpression(#"^([0-9]{4})$", ErrorMessage = "Please enter last 4 digits of your user Id.")]
[Display(Name = "Last 4 digits of user Id")]
public int? UserId{ get; set; }
But if I type in 0645, it throws an error "Please enter last 4 digits of your user Id.".If I change it to say 4567, it works fine. So how should I fix my regex?
You do not have any problem with your regex. As was already said in the comments, your property is an integer and when you set its value to 0645 internally it is converted to int and become 645.
If you look into RegularExpressionAttibute class, line 59, on GitHub you will realize that the method IsValid receives and object and then parses it as a string.
So lets look at the complete flow of your data.
1) Your user types a value into a textbox. ("0645")
2) ModelBinder converts the string typed into an integer. (645)
3) Inside RegularExpressionAttibute.IsValid your integer is converted again into an string ("645")
4) Regular Expression is applied to the value ("645") not ("0645"). So it will not pass your validation.
This is the RegularExpressionAttibute.IsValid method.
override bool IsValid(object value) {
this.SetupRegex();
// Convert the value to a string
string stringValue = Convert.ToString(value, CultureInfo.CurrentCulture);
// Automatically pass if value is null or empty. RequiredAttribute should be used to assert a value is not empty.
if (String.IsNullOrEmpty(stringValue)) {
return true;
}
Match m = this.Regex.Match(stringValue);
// We are looking for an exact match, not just a search hit. This matches what
// the RegularExpressionValidator control does
return (m.Success && m.Index == 0 && m.Length == stringValue.Length);
}
Whats the solution / suggestion?
You are expecting 4 digits as an input, and until now you don't said anything about have to do any kind of calculation with this.
As you don't need to do any calculation you can keep it as an string without any harm. Just keep validating that your string contains 4 digits (you are already doing it).
And if you need to do any calc in the future just convert the string to integer when its needed.
So just change this line:
public int? UserId{ get; set; }
To this:
public string UserId{ get; set; }
How can I properly validate a price field when doing postback?
I have already checked: How can I validate a currency field? but that doesn't fulfil my expectations.
I've tried with (and some variations):
[Range(0, (double)decimal.MaxValue)]
[DataType(DataType.Currency, ErrorMessage = "...")]
public decimal? Price {get; set;}
Problems:
It never uses the [DataType...] attribute to perform validations.
When the value used is not of decimal type, the issued validation error will be a standard English message that I don't know how to customize and need to.
If I make it string instead of decimal?, then the range validation will be thrown for non-decimal or negative values, but it will still allow values like: 1.23456, which is not the currency format I'm expecting.
I'm looking for a built-in approach before I have to create my own custom validation or regular expression. Something like:
[EmailAddress()]
public string ContactEmail {get; set; }
This perfectly suits me!
You can use FluentValidation. You create your own validator class inheriting from : AbstractValidator and inside the constructor you can put all your logic.
MyCurrencyValidatorMyClass : AbstractValidator<MyClass>
{
MyCurrencyValidatorMyClass()
{
RuleFor(x => x.MyField).NotNull().GreatherThan(0);
//All your rules
}
}
var validator = new MyCurrencyValidatorMyClass();
var myClassVar = new MyClass();
validator.Validate(myClassVar);
Also you can integrate your validator with MVC, for reference please see
https://fluentvalidation.codeplex.com/wikipage?title=mvc
For decimal reference see
https://github.com/JeremySkinner/FluentValidation/blob/master/src/FluentValidation/Validators/ScalePrecisionValidator.cs
This is the nuget package https://www.nuget.org/packages/FluentValidation
You can try this RegEx on your Price model property. It will check for strings in the format of "XXXX.XX" where X is a numeric digit (0-9):
[RegularExpression(#"\d{1,20}(\.\d{1,2})?", ErrorMessage = "Invalid Price. Please use the format of XXXX.XX.")]
The first range d{1, 20} allows up to twenty digits before the decimal place. The second range d{1, 2} allows up to two decimal places.
I have a double variable :
public double Width { set; get; }
I want to validate the number and display an error message so I added:
[Range(0.0, Double.MaxValue, ErrorMessage = "Width must be a valid number")]
It works great if I enter a negative number, but if I leave it empty or enter letters - the inner error message is
"Input string was not in a correct format."
I'm not usign #html.validationmessagefor , because I need to handle the ModelState's ErrorMessage or error.exception.InnerException.message manually.
How can I fix that?
it seems that this error message comes from a double.Parse
the Data Annotation attributes are not used by the double class, they are just used by some frameworks.
anyway it looks like your input string was no valid double, so a range validation has nothing to do with a valid double string.
So at the moment our ERP/PSA software produces an EFT (Electronic Fund Transfer) .txt file which contains Bank and employee bank information which is then sent to the bank.
Problem is as follows the format to which the EFT File is currently being produced is US standard and not suitable to Canadian bank standards. But I have the required canadian bank standard format.
The format of the file is all about number of columns in a file and the number of characters they contain (if the data for the column doesnt reach the number of characters it is filled with spaces).
So I.e.
1011234567Joe,Bloggs 1234567
And for example lets say I try transform to Canadian Standard
A101Joe,Bloggs 1234567 1234567
Where for example "A" needs to be added to first line in the record.
I'm just wondering how to go about a task like this in C#
I.e.
Read in text file.
Line by Line parse data in terms of start and end of characters
Assign values to variables
Rebuild new file with these variables with different ordering and additional data
I don't have my IDE open so my syntax might be a tad off, but I'll try to point you in the right direction. Anyways, what fun would it be to give you the solution outright?
First you're going to want to get a list of lines:
IEnumerable<string> lines = text.Split('\n');
You said that the columns don't have delimiters but rather are of fixed widths, but you didn't mention where the columns sizes are defined. Generally, you're going to want to pull out the text of each column with
colText = line.Substring(startOfColumn, lengthOfColumn);
For each column you'll have to calculate startOfColumn and lengthOfColumn, depending on the positions and lengths of the columns.
Hopefully that's a good enough foundation for you to get started.
I think that your best bet is to create a class to hold the logical data that is present in the file and have methods in this class for parsing the data from a given format and saving it back to a given format.
For example, assume the following class:
public class EFTData
{
public string Name { get; set; }
public string RoutingNumber { get; set; }
public string AccountNumber { get; set; }
public string Id { get; set; }
public void FromUSFormat(string sLine)
{
this.Id = sLine.Substring(0, 3);
this.RoutingNumber = sLine.Substring(3, 7);
this.Name = sLine.Substring(10, 20);
this.AccountNumber = sLine.Substring(30, 7);
}
public string ToCanadianFormat()
{
var sbText = new System.Text.StringBuilder(100);
// Note that you can pad or trim fields as needed here
sbText.Append("A");
sbText.Append(this.Id);
sbText.Append(this.RoutingNumber);
sbText.Append(this.AccountNumber);
return sbText.ToString();
}
}
You can then read from a US file and write to a Canadian file as follows:
// Assume there is only a single line in the file
string sLineToProcess = System.IO.File.ReadAllText("usin.txt");
var oData = new EFTData();
// Parse the us data
oData.FromUSFormat(sLineToProcess);
// Write the canadian data
using (var oWriter = new StreamWriter("canout.txt"))
{
oWriter.Write(oData.ToCanadianFormat());
}
var lines = File.ReadAllLines(inputPath);
var results = new List<string>();
foreach (var line in lines)
{
results.Add(string.Format("A{0}", line));
}
File.WriteAllLines(outputPath, results.ToArray());