How can I use multiple regex expressions with different validation messages - asp.net-mvc

Requirements
I want to check password policies by using multiple regex expressions.
For each policy violation I want to display a specific validation message.
Examples:
You need to use at least 2 numbers
You need to use at least one upper and one lower case letter
You need to use at least 8 letters
...
Attempt
I tried to use multiple regex expressions (Fluent Validation Match(string expression)), but ASP.NET MVC does not allow to have multiple regex expressions.
The following validation type was seen more than once: regex
Question
How can I use multiple regex validators in Fluent Validation?

You can use custom method defined in Abstract validator:
public class UserValidator : AbstractValidator<User> {
public UserValidator () {
Custom(user => {
Regex r1 = define regex that validates that there are at least 2 numbers
Regex r2 = define regex for upper and lower case letters
string message = string.Empty;
if(!r1.IsMatch(user.password))
{
message += "You need to use at least 2 numbers.";
}
if(!r2.IsMatch(user.password))
{
message += "You need to use at least one upper and one lower case letter.";
}
return message != string.Empty;
? new ValidationFailure("Password", message )
: null;
});
}
}

Related

Should I use Exceptions while parsing complex user input

when looking for Information when and why to use Exceptions there are many people (also on this platform) making the point of not using exceptions when validating user-input because invalid input is not an exceptional thing to happen.
I now have the case where I have to parse a complex string of user input and map it to an Object-Tree basically, similar to a Parser.
Example in pseudo code:
input:
----
hello[5]
+
foo["ok"]
----
results in something like that:
class Hello {
int id = 5
}
class Add {}
class foo {
string name = 'ok'
}
Now in order to "validate" that input I have to parse it, having code that parses the input for validation and code to create the objects separately feels redundant.
Currently I'm using Exceptions while parsing single tokens to collect all Errors.
// one token is basically a single
try {
foreach (token in tokens) {
factory = getFactory(token) // throws ParseException
addObject(factory.create(token)) // throws ParseException
}
} catch (ParseException e) {
// e.g. "Foo Token expects value to be string"
addError(e)
}
is this bad use of exceptions?
An alternative would be to inject a validation class in every factory or mess around with return types (feels a bit dirty)
If exceptions work for your use case, go for it.
The usual problem with exceptions is that they don't let you fix things up and continue, which makes it hard to implement parser error recovery. You can't really fix up a bad input, and you probably shouldn't even in cases where you could, but error recovery lets you report more than one error from the same input, which is often considered convenient.
All of that depends on your needs and parsing strategy, so there's not a lot of information to go on here.

Storing line number in ANTLR Parse Tree

Is there any way of storing line numbers in the created parse tree, using ANTLR 4? I came across this article, which does it but I think it's for older ANTLR version, because
parser.setASTFactory(factory);
It does not seem to be applicable to ANTLR 4.
I am thinking of having something like
treenode.getLine()
, like we can have
treenode.getChild()
With Antlr4, you normally implement either a listener or a visitor.
Both give you a context where you find the location of the tokens.
For example (with a visitor), I want to keep the location of an assignment defined by a Uppercase identifier (UCASE_ID in my token definition).
The bit you're interested in is ...
ctx.UCASE_ID().getSymbol().getLine()
The visitor looks like ...
static class TypeAssignmentVisitor extends ASNBaseVisitor<TypeAssignment> {
#Override
public TypeAssignment visitTypeAssignment(TypeAssignmentContext ctx) {
String reference = ctx.UCASE_ID().getText();
int line = ctx.UCASE_ID().getSymbol().getLine();
int column = ctx.UCASE_ID().getSymbol().getCharPositionInLine()+1;
Type type = ctx.type().accept(new TypeVisitor());
TypeAssignment typeAssignment = new TypeAssignment();
typeAssignment.setReference(reference);
typeAssignment.setReferenceToken(new Token(ctx.UCASE_ID().getSymbol().getLine(), ctx.UCASE_ID().getSymbol().getCharPositionInLine()+1));
typeAssignment.setType(type);
return typeAssignment;
}
}
I was new to Antlr4 and found this useful to get started with listeners and visitors ...
https://github.com/JakubDziworski/AntlrListenerVisitorComparison/

Interpolation in Concrete Syntax Matching

I'm working with a Java 8 grammar and I want to find occurrences of a method invocation, more specifically it.hasNext(), when it is an Iterator.
This works:
visit(unit) {
case (MethodInvocation)`it . <TypeArguments? ta> hasNext()`: {
println("found");
}
}
Ideally I would like to match with any identifier, not just it.
So I tried using String interpolation, which compiles but doesn't match:
str iteratorId = "it";
visit(unit) {
case (MethodInvocation)`$iteratorId$ . <TypeArguments? ta> hasNext()`: {
println("achei");
}
}
I also tried several other ways, including pattern variable uses (as seen in the docs) but I can't get this to work.
Is this kind of matching possible in rascal? If yes, how can it be done?
The answer specifically depends on the grammar you are using, which I did not look up, but in general in concrete syntax fragments this notation is used for placeholders: <NonTerminal variableName>
So your pattern should look something like the following:
str iteratorId = "it";
visit(unit) {
case (MethodInvocation)`<MethodName name>.<TypeArguments? ta>hasNext()`:
if (iteratorId == "<name>") println("bingo!");
}
That is assuming that MethodName is indeed a non-terminal in your Java8 grammar and part of the syntax rule for method invocations.

Store phoneNumbers in Grails Domain Classes?

I want to store phone numbers in Grails domain classes. I am not sure what is the best way of doing this. Storing as int does not seems to be a good idea because leading zero is impossible for that.
What is the best way to store and validate phone numbers in Grails domain classes?
I would store phone as a String - nullable and blank too. For display purposes, simply provide your own tag in grails's tablib package.
For example, with a property inside some domain class like this:
String phone
And a taglib class like this:
class MyTagLib {
static defaultEncodeAs = [taglib:'html']
def phone334 = { attrs ->
String phone = attrs.phone
def formatted =
"(".concat(phone.substring(0, 3)).concat(") ")
.concat(phone.substring(3, 6)).concat("-").concat(phone.substring(6))
out << formatted
}
}
and a usage like this inside a gsp:
<g:phone334 phone="${theInstance.phone}" />
Then if phone = '4165557799', the output would be displayed like this: (416) 555-7799.
You can build as many formatters as you want; for example, if your number is 011218213334488 and you need it to look like +(218) 21 333 4488, simply build a formatter for that depending on the length and/or the pattern detected in the input.
You can also build simple validators right there too to make sure for example that all characters are made up of digits and parentheses and dashes, but I don't think taglibs are the right place for that - perform a bit of filtering and validation as suggested in the other posts before getting to displaying what should be correct input material.
You could most probably use matches constraint and store phone numbers as String as there is no predefined constraints for phone numbers. There in matches you can use any regex pattern required according to your needs.
static constraints = {
phone(matches: "^(?:0091|\\+91|0)[7-9][0-9]{9}$")
}
The above regex will work like :-
Begins with 0, +91 or 0091
Followed by a 7-9
Followed by exactly 9 numbers
Must match entire input
You can change it according to your needs.
You can store the phone number as string. To validate the phone number you can use google phone number java library to validate international numbers. Or more easily you can use this grails plugin in your code: https://github.com/ataylor284/grails-phonenumbers . Here is a sample from the plugin home page.
class MyDomain {
String phoneNumber
static constraints = {
phoneNumber(phoneNumber: true)
}
}
Edit:
To validate the number if it is not blank you have to define your custom constraint class which extends PhoneNumberConstraint class.
class CustomPhoneNumberConstraint extends PhoneNumberConstraint{
#Override
protected void processValidate(target, propertyValue, Errors errors) {
//check if phone number is blank
if (propertyValue instanceof String && GrailsStringUtils.isBlank((String)propertyValue)) {
if (!blank) {
super.processValidate(target,propertyValue, errors)
}
}
return true
}
}

Change Grails REST format /controller/<id>/<action>

I messed around with this a bit yesterday and failed miserably. I want to convert:
"/$controller/$action?/$id?"
To
#in psudo
"/$controller/$id?/$action?"
#ideal regex
"\/(\w+)(\/\d+)?(\/\w+)?"
The most obvious way failed "/$controller/$action?/$id?"
I can write the regex's to do it, but I am having trouble finding a way to using true regexs (I found RegexUrlMapping but could not find out how to use it), and also can't find documentation on how to assign a group to a variable.
My question is 2 parts:
How to I define a URL Resource with a true regex.
How to I bind a "group" to a variable. In other words if I define a regex, how do I bind it to a variable like $controller, $id, $action
I would also like to be able to support the .json notation /user/id.json
Other things I have tried, which I thought would work:
"/$controller$id?$action?"{
constraints {
controller(matches:/\w+/)
id(matches:/\/\d+/)
action(matches:/\/\w+/)
}
}
also tried:
"/$controller/$id?/$action?"{
constraints {
controller(matches:/\w+/)
id(matches:/\d+/)
action(matches:/\w+/)
}
}
The grails way to deal with this is to set
grails.mime.file.extensions = true
in Config.groovy. This will cause Grails to strip off the file extension before applying the URL mappings, but make it available for use by withFormat
def someAction() {
withFormat {
json {
render ([message:"hello"] as JSON)
}
xml {
render(contentType:'text/xml') {
//...
}
}
}
For this you'd just need a URL mapping of "$controller/$id?/$action?"
I'm not aware of any way to use regular expressions in the way you want in the URL mappings, but you could get a forward mapping working using the fact that you can specify closures for parameter values that get evaluated at runtime with access to the other params:
"$controller/$a?/$b?" {
action = { params.b ?: params.a }
id = { params.b ? params.a : null }
}
which says "if b is set then use that as the action and a as the id, otherwise use a as the action and set id to null". But this wouldn't give you a nice reverse mapping, i.e. createLink(controller:'foo', action:'bar', id:1) wouldn't generate anything sensible, you'd have to use createLink(controller:'foo', params:[a:1, b:'bar'])
Edit
A third possibility you could try is to combine the
"/$controller/$id/$action"{
constraints {
controller(matches:/\w+/)
id(matches:/\d+/)
action(matches:/\w+/)
}
}
mapping with a complementary
"/$controller/$action?"{
constraints {
controller(matches:/\w+/)
action(matches:/(?!\d+$)\w+/)
}
}
using negative lookahead to ensure the two mappings are disjoint.

Resources