I have the following code:
public class Register
{
[RegularExpression(#"^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$", ErrorMessage = "eMail is not in proper format")]
[Required(ErrorMessageResourceName="Name Required"), ErrorMessageResourceType = typeof(ErrorMessages))]
public string Email{ get; set; }
}
Email that i tried: asd#asd.com is valid but it fail the validation.
The required is working, but the regular expression is failing. Even if I enter a valid email address, it will still say that email is not in proper format.
Anything I missed here? Thanks in advance!
EDIT
This regex validator is working on my other mvc application by using Resources.resx. So I think what is wrong here is how I declared it on my model class.
Regex regx = new Regex(#"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
+ #"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
+ #"#[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$");
/* declare in public and validate for your mail text box */
This is solved. I accidentally put the wrong regex on my code:
"^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$
instead of:
#"^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$
Now I will focus on to make the best email regex. Thanks!
Related
I'd like to send a slash command to a channel of my choice.
I'm using the Newtonsoft Json.NET serializer from NuGet. Currently, I have the following code:
string messageToSend = #"/Kyber test task here";
string channelToSendTo = "#general";
var urlWithAccessToken
= "https://hooks.slack.com/services/TOKEN/SPECIFIC/STUFF";
var client = new SlackClient(urlWithAccessToken);
client.PostMessage(username: "MyBot",
text: messageToSend,
channel: channelToSendTo);
And the SlackClient.cs
public SlackClient(string urlWithAccessToken)
{
_uri = new Uri(urlWithAccessToken);
}
public void PostMessage(string text, string username = null, string channel = null)
{
Payload payload = new Payload()
{
Channel = channel,
Username = username,
Text = text
};
PostMessage(payload);
}
public class Payload
{
[JsonProperty("channel")]
public string Channel { get; set; }
[JsonProperty("username")]
public string Username { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}
It currently just says "/kyber test task here" instead of calling the /kyber slash command.
I've seen the undocumented chat.command command, but it doesn't appear to work with the Slack API now. I was hoping there was another way to do it without using the Legacy App functionality, since it surprises me that I was unable to find an example newer than about 3-4 years ago that didn't use it.
I guess this is the answer, but I asked Slack support about it. They replied:
It sounds like you might be asking about allowing an app to send a message containing the slash command, in order to trigger the slash command.
If so, I'm afraid that's not possible. Instead, since all slash commands essentially trigger a specific API endpoint, you'll need to contact the developers of that slash command to see if they make that endpoint publicly accessible so that you can create your own app mechanism to try and trigger commands to those endpoints.
I'm sorry that I don't have better news for you on this. I hope that info might help you to move forward though. Thanks for checking in on this.
So I think the answer is that the App I'm using doesn't support that functionality, and Slack doesn't/won't either. Thanks anyways for the help.
Can we check whether the input form in an adaptive card is filled or not with a warning message.
I am currently using an adaptive card to gather user input in bot application,I have already added isRequired for input validation but it doesnot give any warning message instead when I click on submit it doesnot go to the next method.
As soon as the user presses submit I want to make sure that the form is not empty
If you have an Adaptive Card like this (notice the ID given to the input):
var card = new AdaptiveCard
{
Body =
{
new AdaptiveTextBlock("Adaptive Card"),
new AdaptiveTextInput { Id = "text" },
},
Actions = {
new AdaptiveSubmitAction { Title = "Submit" } },
},
};
You can validate the value sent through the submit action like this:
if (string.IsNullOrEmpty(turnContext.Activity.Text))
{
dynamic value = turnContext.Activity.Value;
string text = value["text"]; // The property will be named after your input's ID
var emailRegex = new Regex(#"^\S+#\S+$"); // This is VERY basic email Regex. You might want something different.
if (emailRegex.IsMatch(text))
{
await turnContext.SendActivityAsync($"I think {text} is a valid email address");
}
else
{
await turnContext.SendActivityAsync($"I don't think {text} is a valid email address");
}
}
Validating email with regex can get very complicated and I've taken a simple approach. You can read more about email Regex here: How to validate an email address using a regular expression?
I took totally different approach than the accepted answer here. If you are going to use adaptive cards a lot in your bot than it makes sense to create card models and have validation attributes applied to each field that needs validation. Create custom card prompt inheriting from Prompt<object> class. Override OnPromptAsync and OnRecognizeAsync and check the validation of each field there.
I want to validate a textbox to accept datetime value using DataAnnotations in MVC3. But I don't have any idea how to do it. Given below is what I'm trying to accomplish my requirement and it's not working.
[DataType(DataType.DateTime, ErrorMessage = "Invalid Datetime")]
[DisplayFormat(DataFormatString = "{0:dd/MM/yyyy HH:mm}")]
[Display(Name = "Start Datetime")]
public DateTime? StartDateTime { get; set; }
As When I click on submit button after filling corrupted data first problem is that form get post and later it shows the message that "Invalid date" and second if I enter just date without time still form get post but this time it does not shows the message which is also wrong.
So I just want to know how can I validate my textbox to accept datetime in "dd/MM/yyyy HH:mm" format only using MVC DataAnnotations .
1. Your client side validation is not working. You are seeing error message after the form is submitted - means client side validation is not working properly. To make the client side validation work, ASP.NET MVC assumes that you have jquery.validate.js and jquery.validate.unobtrusive.js referenced on the page. You can download them using NuGet Package Manager on your Visual Studio.
2. Date field is not being validated. You are expecting the DisplayFormat to validate the date format for you. But actually it does not. That is more of about displaying your date on the View.
In order to validate the date format, you need to use your own custom Attribute. Or you can simply use RegularExpression attribute. The most simple example looks like this:
[RegularExpression(#"\d{1,2}/\d{1,2}/\d{2,4}\s\d{1,2}:\d{1,2}", ErrorMessage = "")]
Or if you want to make a custom attribute, then:
public class DateFormatValidation : ValidationAttribute{
protected override bool IsValid(object value){
DateTime date;
var format = "0:dd/MM/yyyy HH:mm"
bool parsed = DateTime.TryParseExact((string)value, format, System.Globalization.CultureInfo.InvariantCulture, DateTimeStyles.None, out date)
if(!parsed)
return false;
return true;
}
}
Then use it like:
[DataType(DataType.DateTime, ErrorMessage = "Invalid Datetime")]
[DateFormatValidation]
[Display(Name = "Start Datetime")]
public DateTime? StartDateTime { get; set; }
I got it from diff website, saying its a problem in chrome and he has fixed it by applying this code.
So check first if it works in firefox then you might be forced to apply this code, however this code skips checking the date format.
$.validator.methods["date"] = function (value, element) { return true; }
I am trying to validate if the userinput is an email adress (adding a member to database).
The user will enter data in TextBox, when the validating event gets called; I want to check if the input is a valid email adress. So consisting of atleast an # and a dot(.) in the string.
Is there any way to do this through code, or perhaps with a Mask from the MaskedTextbox?
Don't bother with Regex. It's a Bad Idea.
I normally never use exceptions to control flow in the program, but personally, in this instance, I prefer to let the experts who created the MailAddress class do the work for me:
try
{
var test = new MailAddress("");
}
catch (FormatException ex)
{
// wrong format for email
}
Do not use a regular expression, it misses so many cases it's not even funny, and besides smarter people that us have come before to solve this problem.
using System.ComponentModel.DataAnnotations;
public class TestModel{
[EmailAddress]
public string Email { get; set; }
}
Regex for simple email match:
#"\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b"
Regex for RFC 2822 standard email match:
#"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
See: How to: Verify that Strings Are in Valid Email Format - MSDN
The Regex you are looking should be:
"^(?("")(""[^""]+?""#)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])#))
(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,24}))$"
(From the same source)
I recommend you use this way and it's working well for me.
Regex reg = new Regex(#"\w+([-+.]\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*");
if (!reg.IsMatch(txtEmail.Text))
{
// Email is not valid
}
I suggest that you use a Regular Expression like:
#"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
To validate the input of your textbox.
Example code:
private void button1_Click(object sender, EventArgs e)
{
Regex emailRegex = new Regex(#"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?
^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+
[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
if (emailRegex.IsMatch(textBox1.Text))
{
MessageBox.Show(textBox1.Text + "matches the expected format.", "Attention");
}
}
Edit: I found a better, more comprehensive Regex.
I need to validate a folder name in c#.
I have tried the following regex :
^(.*?/|.*?\\)?([^\./|^\.\\]+)(?:\.([^\\]*)|)$
but it fails and I also tried using GetInvalidPathChars().
It fails when i try using P:\abc as a folder name i.e Driveletter:\foldername
Can anyone suggest why?
You could do that in this way (using System.IO.Path.InvalidPathChars constant):
bool IsValidFilename(string testName)
{
Regex containsABadCharacter = new Regex("[" + Regex.Escape(System.IO.Path.InvalidPathChars) + "]");
if (containsABadCharacter.IsMatch(testName) { return false; };
// other checks for UNC, drive-path format, etc
return true;
}
[edit]
If you want a regular expression that validates a folder path, then you could use this one:
Regex regex = new Regex("^([a-zA-Z]:)?(\\\\[^<>:\"/\\\\|?*]+)+\\\\?$");
[edit 2]
I've remembered one tricky thing that lets you check if the path is correct:
var invalidPathChars = Path.GetInvalidPathChars(path)
or (for files):
var invalidFileNameChars = Path.GetInvalidFileNameChars(fileName)
Validating a folder name correctly can be quite a mission. See my blog post Taking data binding, validation and MVVM to the next level - part 2.
Don't be fooled by the title, it's about validating file system paths, and it illustrates some of the complexities involved in using the methods provided in the .Net framework. While you may want to use a regex, it isn't the most reliable way to do the job.
this is regex you should use :
Regex regex = new Regex("^([a-zA-Z0-9][^*/><?\"|:]*)$");
if (!regex.IsMatch(txtFolderName.Text))
{
MessageBox.Show(this, "Folder fail", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
metrotxtFolderName.Focus();
}