Regex is not working in RegularExpression attribute on c# - c#

guys, I don't know this question is already present or not but I have tried every search, so my question is why my regex is not working properly in RegularExpression attribute. this same regex I have used in javascript and this is working on javascript. can anyone help me what I am doing wrong here?
[Required]
[Display(Name = "First name")]
[MaxLength(50)]
[RegularExpression("^(?![#\\+\\-=\\*])", ErrorMessage = "First Name Should not start with these characters #, +, =, *, -")]
public string firstname { get; set; }
I am using this regex for validating the First Name should not start with #,+,=,*,-.
I have already spent 3 hours to figure out what I am doing wrong here.

I believe you regex should look like this:
^(?![#\\+\\-=\\*]).*
Here is a working example.

Your regex is invalid. Here is the updated one, which works as you expected:
^(?![#\\+\-\\=\\*])

Related

C# Regular Expression Attribute not working as expected

I am using the RegularExpression attribute to verify multiple email addresses on one input in my view model. The ErrorMessage keeps coming up on field. I have validated my RegEx on 5 different online test sites and they all test positive.
Here is my code:
[RegularExpression(#"\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*([,;\s]+\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*){0,7}", ErrorMessage = "Please enter a valid email address. For multiple addresses please use a comma or semicolon to separate the email addresses.")]
public string EmailAddresses { get; set; }
If I enter an email address it works, if I enter two email addresses without spaces it works, but if I add a space it breaks. I added the '\s' to include white spaces and it does work on the online testers I have tried but it will not work in my application.
The expected valid result should be:
'test#test.com, test2#test.com, test3#test.com'
However, this it coming back as invalid. If I use the exact same sequence with no spaces it is valid.
Kendo UI is checking the validation of the form before sending it to the controller.
Any help is very appreciated. Thank you in advance.
Try this pattern:
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"
You don't need "#" symbol. I tested your pattern at http://regexstorm.net/tester and it is correct match for test#test.com, test2#test.com, test3#test.com . Use construct below
public class LoginViewModel
{
[RegularExpression("\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*([,;\s]+\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*){0,7}", ErrorMessage = "Please enter a valid email address. For multiple addresses please use a comma or semicolon to separate the email addresses.")]
public string EmailAddresses { get; set; }
}
For it to work in ASP.NET MVC Framework ensure you do the have the following on the view
<input type="text" id ="EmailAddresses" name="EmailAddresses"/>
The id and name attributes are required for it to validate. You can do this manually as above or use #Html.EditorFor(model => model.EmailAddresses) which will create the id and name attributes for you
I found the issue. In the end it had nothing to do with C#. The problem was I was using Kendo UI on the front end, as updated in the main post. Keno UI had to also receive the RegEx update sent by Andrew to solve the issue. I will make Andrew as the correct solution as his RegEx did work for me. I was totally turn around by the server side/client side difference as I am new to this. Thank you all for your help.

Parsing with Regex

I've been searching for a good guide on this, but I can't quite figure out the regex syntax.
I have the following string that I need parsed:
[ 2013.11.22 22:50:30 ] System > Firstname Surname was kicked by
Moderator
The variables I need to pull out should look a bit like this:
[ <yyyy>.<MM>.<dd> <hh>:<mm>:<ss> ] System > <username> was kicked by <moderatorname>
So, basically the timestamp and who was kicked by who (alpha-numeric names). Here's what's confusing me a little. Both the username and the name of the moderator could potentially be
in 2 or even 3 parts divided by spaces... and potentially I guess the username could be "was kicked" which surely could screw with the parsing.
I haven't done alot of regex before, so I'm not that good at the syntax. Looking at a few guides I've come this far:
string text = "[ 2013.11.22 22:50:30 ] System > Firstname Surname was kicked by Moderator"
var input = text.ToLower();
Match m = Regex.Match(input, #"(?i:\[\s)(?<year>\d{4})\.(?<month>\d{1,2})\.(?<day>\d{1,2})\s(?<hour>\d{1,2})\:(?<minute>\d{1,2})\:(?<second>\d{1,2})\s\]");
This works for parsing the timestamp, but the text part following is giving me some trouble. I'm not really sure how to approach the issue.
Any help is appreciated, thank you
use this :
\[\s*(?<yyyy>\d+)\.(?<MM>\d+)\.(?<dd>\d+)\s+(?<hh>\d+)\:(?<mm>\d+)\:(?<ss>\d+)\s+\] System > (?<username>.+) was kicked by (?<moderatorname>\w+)
demo here :
http://regex101.com/r/kU2xA8
It may be your intention to only use regex, if so, fair enough. Otherwise may I suggest this could be simpler for the date part.
string date = "2013.11.22 22:50:30";
DateTime dateTime = DateTime.ParseExact(date , "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
or use DateTime.Parse() if there's less certainty about the format.
I'll have a look at one big regex, but my approach would be to just pickup the usernames with regex with something like this:
System > (((?!System|\swas).)+)\swas (whoops, I'm picking up addition things)
and
(?<=kicked by).*

Prevent html tags entries in mvc textbox using regular expression

I want to prevent any html tags (written between "<>") in a textbox in my mvc 4 application.
I have given the data annotation regular expression for my property as follows:
[RegularExpression(#"<[^>]*>",ErrorMessage="Invalid entry")]
public string Name { get; set; }
But the regular expression not working correctly. When I type , it shows "Invalid entry".After that, when I type some normal text like "praveen" also shows "Invalid entry" error message.
I have tried another regular expressions something like #"<[^>]*>" ,but same result as above.
Please help.
You have to logic turned around. The regex you have written is what you do not want to allow, whereas the RegularExpression attribute requires you to enter what you do allow. Anything not matching your regex will show the ErrorMessage.
An alternative regex could be:
#"[^<>]*"
which would disallow < and >.
RegularExpression to avoid any html tags entry use:
[RegularExpression("^[^<>,<|>]+$", ErrorMessage = "Html tags are not allowed.")]

How to find string between some characters using regex in c#

Good day~
I am not really good at this regular expression.
So I need your help, please.
Condition:
Users can input their email addressed and name together.
I want to extract email address and user name out of string.
string pattern1 = "Peter Jackson<peter#jackson.com>";
From that string I want to get "Peter Jackson" and "<peter#jackson.com>".
string pattern2 = "Peter Jackson(peter#jackson.com)";
However, people always make mistakes like below.
And they can also use "[" instead of "<".
so...
string pattern3 = "Peter Jackson[peter#jackson.com]";
Even some stupid users can input like...
string pattern4 = "Peter Jackson{peter#jackson.com}";
So, I had to look for the characters which are "<", "(", "[" and "{".
I tried
string regularExpressionPattern = #"^(<|(|[|{)(.*?)^(}|]|)|>)";
But I think I've done something wrong.
And I also try to think that people could input more mistake like....
string pattern5 = "Peter Jackson<peter#jackson.com>mistake";
Could anyone help this problem?
Advanced thanks.
PS: I know how to split string with a character. So it won't help. I needa proper regular expression.
I believe the regular expression you are looking for is as follows:
(.*?)[<([{](.*?)[>)\]}]
You would want group 1 and group 2.
(.*?)[([<{](.*?)[)\]>}]
I believe this should be adequate.
The name will be in the first captured group, and the email will be in the second.
Seems like (.*)[<\(\[{](.*)[>\)]}] works for me.
Groups for the name, and the email address as well.
http://regexr.com?33sq4 is my test.

Unable to replace placeholder {0} in ErrorMessage of a RegularExpressionAttribute

[StringLength(100),
RegularExpression(RegexPatterns.NoBracketsRegEx,
ErrorMessageResourceType = typeof(Resources),
ErrorMessage = "HTML tags are not allowed in {0} field")]
public virtual string Title { get; set; }
When I try to enter Html tags in Title field I am getting the error message:
"HTML tags are not allowed in {0} field"
instead of
"HTML tags are not allowed in Title field".
I am using System.ComponentModel.DataAnnotations, Version=4.0.0.0
I have tried setting Display(Name="Title") but still no luck!! Any idea what's going wrong?
You can't use ErrorMessage and ErrorMessageResourceType together. Their use is mutually exclusive.
For non-localized error messages, you can use the ErrorMessage property initialized with a string literal (without format specifiers because, like you've discovered, they will be shown as is).
For localized error messages, use the ErrorMessageResourceType property together with the ErrorMessageResourceName property.
Here's are a couple of related blog posts that may help:
Localizing Validation Using DataAnnotations, and
ASP.NET MVC 2: Model Validation.

Categories

Resources