Custom Regex validation firing on all inputs - regex

I'm writing a .NET MVC application and using unobtrusive validation to sanitize my client inputs based on data annotations in my model. I have an input that I do not want to allow HTML tags into and would like to display a custom error message if an html tag is entered. As such I have created a data annotation with a custom regex expression to cover these conditions, like so:
[Required(ErrorMessage = "You must provide a First Name.")]
[RegularExpression(#"<[a-z][\s\S]*>", ErrorMessage = "Invalid character")]
[DisplayName("First Name")]
public string FirstName { get; set; }
The issue with this is, no matter what character, whether it be <test> or whether it be abc will cause the Invalid Character message to appear. The required attribute works fine, and if I try a simple regex such as:
[RegularExpression("[a-z]", ErrorMessage = "Invalid character")]
This works 100% as expected, leading me to believe my regex is incorrect, nut I know it works for HTML validation as I can prove it out with online tools. What am I doing wrong?

If you take a look at the documentation of the RegularExpressionAttribute, it states:
Specifies that a data field value in ASP.NET Dynamic Data must match the specified regular expression.
So your attribute is doing the exact opposite of what you want to do is:
[RegularExpression(#"^(?!.*<.*>).*$", ErrorMessage = "Invalid character")]

Related

Laravel 4 regex email validation

I am trying to add validation, inside my User model to validation emails using regex.
However, it's spits a dummy out at the first apostrophe.
'email' => 'required|regex:/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+#[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/',
Have you tried the 'email' validation rule?
'email' => 'required|email|unique:users,email'
http://laravel.com/docs/4.2/validation#rule-email
As the answer to this question on SO states, there is no simple regular expression to validate an email-address. Using your RegEx could maybe catch valid addresses (although that's just speculation of mine). Using the email-validation-rule would be my first choice.
But you are right, this is just the server side in the first place, if you ignore redirecting users back with input and error messages..
On the client-side, you would have some options. The first one would be to simply rely on the build in browser-validation, by declaring the corresponding input-field as an email-address which you should do anyway:
{{ Form::email($name, $value = null, $attributes = array()) }}
Another, more advanced way would be to create some kind of helper to check the typed input via Ajax using the same validation rule and returning the error messages or sth. similar. This could be an additional route to your Model-Resource for example. This way, you would be stable and consistent.

Custom regex validation in Play Framework - Scala

I am new to Play 2.3.x and Scala and trying to implement a form input validation.
Let us say I have an example form.
val userForm = Form(
"firstName" -> nonEmptyText
)
I want to implement something like this for the first name field:
If a regex for first name (say firstName.regex = “regex for first name” ) is defined then {
Validate first name against specific regex
}else{
Validate against the global regex ( say global.regex = “global regex white list some regex valid for across the application”)
}
Also, I want to combine this with multiple (chained/step wise) validations so as to be able to display :
If nothing is entered - Please First name
If first name is enetred and fails regex validation - Please enter a valid first name
I want to develop a generic solution so that I can use it for all the fields.
Appreciate any help.
You can use verifying.
val userForm = Form(
"firstName" -> nonEmptyText.verifying("Must contain letters and spaces only.", name => name.isEmpty || name.matches("[A-z\\s]+") )
)
There's a little extra logic there (name.isEmpty with OR), because an empty string would trigger both validation errors. It seems like the validation errors are kept in order in which they're triggered, so you might be able to get away with using the first validation error in the sequence, but don't hold me to that. You can chain as many verifyings together as you like.
I'm not entirely sure what you have in mind by making these more generic, but you can make your own Mapping validators by composing already existing ones in the Forms object.
val nonEmptyAlphaText: Mapping[String] = nonEmptyText.verifying("Must contain letters and spaces only.", name => name.matches("[A-z\\s]+") )
And then you can use it in the Form:
val userForm = Form(
"firstName" -> nonEmptyAlphaText
)

WCF RIA Services DataAnnotations not working as expected

I'm having a hard time understanding why my DataAnnotation attributes aren't be used by the client DataForm. Below is the metadata attribute on a phone number field.
[DataType(DataType.PhoneNumber, ErrorMessage = "Please provide a valid phone number.")]
public string client_phone_home { get; set; }
When running the application, I can enter any string less than 10 digits in length. It can be letters, numbers, etc. If I enter more than 10 characters, the datavalidation throws a message saying that the client_phone_home field must be a string less than 10 characters in length. It doesn't use my error message, and doesn't indicate anything about the field requiring a valid phone number.
Anyone know why this dataannotation is not working on the client side?
Check this http://www.silverlightshow.net/items/WCF-RIA-Services-Part-6-Validating-Data.aspx .It has complete explaination about Data Annotation Validation Attributes,Custom Validation Attributes,Server-Side Validation.
and look into this also http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2010/07/27/silverlight-and-wcf-ria-services-6-validation.aspx

Regular expression for validating url with parameters

I have been searching high and low for a solution to this, but to no avail. I am trying to prevent users from entering poorly formed URLs. Currently I have this regular expression in place:
^(http|https)\://.*$
This does a check to make sure the user is using http or https in the URL. However I need to go a step further and validate the structure of the URL.
For example this URL: http://mytest.com/?=test is clearly invalid as the parameter is not specified. All of the regular expressions that I've found on the web return valid when I use this URL.
I've been using this site to test the expressions that I've been finding.
Look I think the best solution for testing the URL as :
var url="http://mytest.com/?=test";
Make 2 steps :
1- test only URL as :
http://mytest.com/
use pattern :
var pattern1= "^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}([0-9A-Za-z]+\.)([A-Za-z]){2,3}(\/)?";
2- split URL string by using pattern1 to get the URL query string and IF URL has Query string then make test on It again by using the following pattern :
var query=url.split(pattern1);
var q_str = query[1];
var pattern2 = "^(\?)?([0-9A-Za-z]+=[0-9A-Za-z]+(\&)?)+$";
Good Luck,
I believe the problem you are having comes from the fact that what is or is not a valid parameter from a query string is not universally defined. And specifically for your problem, the criteria for a valid query is still not well defined from your single example of what should fail.
To be precise, check this out RFC3986#3.4
Maybe you can make up a criteria for what should be an "acceptable" query string and from that you can get an answer. ;)

RegularExpressionAttribute fails validating right data

I have a regular expression that works great when I try it:
System.Text.RegularExpressions.Regex.IsMatch("universal",#"^[A-Za-z0-9 ._’&-/s]{0,100}$")
true
System.Text.RegularExpressions.Regex.IsMatch("universal £$%$£%",#"^[A-Za-z0-9 ._’&-/s]{0,100}$")
false
But when I use it as a validation filter:
[RegularExpression(#"^[A-Za-z0-9 ._’&-/s]{0,100}$", ErrorMessage = "The parameter is not valid")]
It works in the client side, but it does not work on the server side. For example when I pass the word "universal" the ModelState contains an error regarding the field marked with that regex validator.
This attribute is the only validation rule applied to that field, what may be the problem?
Cheers.