In the following code, the
I'd like to improve the performance by putting the RegExp object somewhere, but I can't figure out how to do the nest.
#ValidatorConstraint()
export class RegExp implements ValidatorConstraintInterface {
validate(kana: string, args: ValidationArguments) {
const str = new RegExp(/^[ァ-ヶー]+$/)
return str.test(kana)
}
defaultMessage(args: ValidationArguments) {
return 'Text should be'
}
}
thanks
If you need regexp only - simply use a built-in Matches validator:
#Matches(/^[ァ-ヶー]+$/)
public field: string;
In this case it will reuse regexp on every validation.
I thought of it this way.
const regexp = new RegExp(/^[ァ-ヶー]+$/)
#ValidatorConstraint()
export class RegExp implements ValidatorConstraintInterface {
validate(kana: string, args: ValidationArguments) {
return regexp.test(kana)
}
defaultMessage(args: ValidationArguments) {
return 'Text should be'
}
}
Related
I use loopback4. How do I make an expression to match datetime with time zone.I am interested by the hour parameter only: "finalhour"
example: 2019-12-20T10:22:50.143Z ==> 2019-12-20Tfinalhour:22:50.143Z
I tried with this: const pattern=await '^'+"T"+finalhour+'^'
but loopback usually read it as ^T10^
I'm resort to you after a long search in the forums.I will be thankful if you help me
From what i understand, you want to build a regex that match 2019-12-20TsomeNumber:22:50.143Z.
You could use this default ISO datetime regex
(\d{4})-(\d{2})-(\d{2})T(\d{2})\:(\d{2})\:(\d{2})\.\d{3,4}Z
And modify it to take your finalhour variable in it.
let finalHour = 10;
// when building regex from constructor, we need to espace the backslash ( \ )
// i did not know that.
let regex = new RegExp('(\\d{4})-(\\d{2})-(\\d{2})T' + finalHour + '\\:(\\d{2})\\:(\\d{2})\\.\\d{3,4}\\Z');
let test = '2019-12-20T10:22:50.143Z';
console.log(regex.test(test));
Also, you don't need an await keyword here because your are building a string, not waiting for a promise.
I need to return the number of order per hour. so i try this solution but it return false comparison, for example if i have one order at hour:10 it return 6
#get('/orders/count-perHour/{date}', {
responses: {
'200': {
description: 'Order model count',
content: { 'application/json': { schema: CountSchema } },
},
},
})
async countPerHour(
#param.path.string('date') date: string): Promise<any> {
let dateStart = new Date(date);
dateStart.setSeconds(0);
dateStart.setMinutes(0);
let dateEnd = new Date(date);
dateEnd.setSeconds(59);
dateEnd.setMinutes(59);
return await this.orderRepository.count(
{
createdAt: {
lte: dateEnd
,
gte: dateStart
}
}
);
}
I am trying to use conventions in my unit tests which make use of AutoFixture. I have a Password value object as shown:
public class Password : SemanticType<string>
{
private int _daysPasswordValid;
public Password(string password) : base(IsValid, password)
{
Guard.NotNullOrEmpty(() => password, password);
Guard.IsValid(() => password, password, IsValid, "Invalid Password");
DateCreated = DateTime.Now;
}
static bool IsValid(string candidate)
{
//password cannot contain be whitespace
if (string.IsNullOrWhiteSpace(candidate))
return false;
const string passwordPattern = #"^(?=.*[A-Z].*[A-Z])(?=.*[!##$&=()-*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{20}$";
var match = Regex.Match(candidate, passwordPattern);
return match.Success;
}
public DateTime DateCreated { get; private set; }
public int DaysPasswordValid
{
get { return _daysPasswordValid; }
set
{
const int minimunDays = 0;
const int maximumDays = 90;
if (value <= maximumDays && value > minimunDays)
_daysPasswordValid = value;
else
throw new ArgumentOutOfRangeException(
"Password must be valid more than {0} and no more than {1} days.".Fmt(minimunDays, maximumDays));
}
}
public static implicit operator string(Password password)
{
return password.Value;
}
public static explicit operator Password(string value)
{
return new Password(value);
}
}
I would like to be able to create a fixture based on the Password class and have the fixture created with a valid password, in other words, a password that matches the RegEx pattern in the Password class. I have been looking at the RegularExpressionGenerator available in AutoFixture but haven't quite gotten things to work. Here is the builder have so far:
public class ValidPasswordBuilder : ISpecimenBuilder
{
public ValidPasswordBuilder(string regularExpressionRequest)
{
PasswordRegularExpression = regularExpressionRequest;
}
public string PasswordRegularExpression { get; private set; }
public object Create(object request, ISpecimenContext context)
{
var pi = request as ParameterInfo;
if (pi != null && pi.Name == "password" && pi.ParameterType == typeof(string))
{
var generator = new RegularExpressionGenerator();
var regExRequest = new RegularExpressionRequest(PasswordRegularExpression);
var result = generator.Create(regExRequest, context);
return result.ToString();
}
return new NoSpecimen(request);
}
}
Here is the test:
[Fact]
public void ValidPasswordMatches()
{
var fixture = new Fixture();
fixture.Customizations.Add(new ValidPasswordBuilder(PasswordPattern));
Action a = () => fixture.Create<Password>();
a.ShouldNotThrow<ArgumentException>();
}
I can run the test as setup above, and it passes, but if I debug it, I get an error in the IsValid function in the Password class (through the Guard clause) that says that the password returned from the builder is:
Ploeh.AutoFixture.Kernel.NoSpecimen
I never seem to get a result that matches the RegEx pattern. I feel like I'm close, but need some help getting over the hump.
Thanks!
As it looks like, the pattern you use is not supported:
^(?=.*[A-Z].*[A-Z])(?=.*[!##$&=()-*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{20}$
Try with a different Regular Expression.
Edit: Or try doing this or this, in order to configure AutoFixture to use a different Regular Expression, without changing the Password class.
AutoFixture turns Regular Expressions into Automatons by applying the algorithms of dk.brics.automaton.
You may use a different pattern or use a different engine to reverse the Regular Expression into an Automaton. As an example, you can use the Rex engine.
Though, even with Rex your Regular Expression is not supported, as the following constructs are currently not supported by Rex:
anchors \G, \b, \B, named groups, lookahead, lookbehind, as-few-times-as-possible quantifiers, backreferences, conditional alternation, substitution.
If you want to try Rex with AutoFixture you can use the following generator:
internal class RexRegularExpressionGenerator : ISpecimenBuilder
{
public object Create(object request, ISpecimenContext context)
{
if (request == null)
return new NoSpecimen();
var regularExpressionRequest = request as RegularExpressionRequest;
if (regularExpressionRequest == null)
return new NoSpecimen();
var pattern = regularExpressionRequest.Pattern;
try
{
var regex = RexEngine
.GenerateMembers(
new RexSettings(pattern) { k = 1 })
.FirstOrDefault();
if (Regex.IsMatch(regex, pattern))
return regex;
}
catch (ArgumentException)
{
return new NoSpecimen(request);
}
return new NoSpecimen(request);
}
}
As far as I can tell, you can download Rex only as a .NET application (.exe) file which you can then reference like any other managed assembly in your project.
I would like to set a RegExp to have a matching judgement with String. I tried to use pattern.test(str), but if pattern is a part of string it will be true. It isn't what i want.
For example, I set my pattern is "/[a-z]/" and str is "abc123", it will be true by pattern.test(str). My prefer result is false, because the str contains "123", not every character is a-z. How can I do that? Thank you!
package {
import flash.display.Sprite;
public class regexp extends Sprite{
var pattern:RegExp=/[a-z]/;
var str:String="abc123";
public function regexp() {
trace(pattern.test(str));
}
}
}
Try this one:
var pattern:RegExp=/^[a-z]+?$/;
I am using MVC 3 with Razor. I can't figure out how to code a string extension regex to take this:
This_is_some_text
to display:
This is some text
I set up some enums for a drop down list, so they appear thusly (obviously I can't create an enum with a space):
public enum MyProperty
{
This_is_some_text,
This_is_some_other_text
}
I just cannot figure out the regex is to do what I want if I am doing this:
public static string EnumToDisplay(this string str)
{
return Regex.Replace(str, "[What is the regex I should use?]");
}
As a bonus for me I would also like to add a period "." to the end of the enum. The reason for this is that I have OCD and my enums are taking the form of short sentences. :)
Thanks!
Why not use String.Replace() for this? RegEx seems a bit overkill.
public static string EnumToDisplay(this string str)
{
return str.Replace('_', ' ') + ".";
}
Why do you want to use regular expressions? A very wise man once said, I quote:
Some people, when confronted with a problem, think "I know, I'll use
regular expressions." Now they have two problems.
How about using the [Display] attribute which is kinda designed exactly for this purpose:
public enum MyProperty
{
[Display(Name = "This is some super text")]
This_is_some_text,
[Display(Name = "And this is some other text")]
This_is_some_other_text
}
and then writing a custom Html helper:
public static class HtmlExtensions
{
public static IHtmlString DisplayForEnum<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
{
if (!typeof(TProperty).IsEnum)
{
throw new ArgumentException("sorry this helper is inteded to be used with enum types");
}
var model = htmlHelper.ViewData.Model;
if (htmlHelper.ViewData.Model == null)
{
return MvcHtmlString.Empty;
}
var field = typeof(TProperty).GetField(expression.Compile()(htmlHelper.ViewData.Model).ToString());
if (field == null)
{
return new HtmlString(htmlHelper.Encode(htmlHelper.ViewData.Model.ToString()));
}
var display = field.GetCustomAttributes(typeof(DisplayAttribute), true).FirstOrDefault() as DisplayAttribute;
if (display == null)
{
return new HtmlString(htmlHelper.Encode(htmlHelper.ViewData.Model.ToString()));
}
return new HtmlString(htmlHelper.Encode(display.Name));
}
}
So now assuming you have a view model:
public class MyViewModel
{
public MyProperty Foo { get; set; }
}
and a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Foo = MyProperty.This_is_some_other_text
};
return View(model);
}
}
you could use the custom helper we just wrote in the view to display a user friendly text that we might have associated to an ugly enum. Hey, now you could even have this working with globalization and multiple languages using resources:
#model MyViewModel
#Html.DisplayForEnum(x => x.Foo)
I do not know about asp.net - but there should be a really simple method that replaces one character with another char. Like:
String.replace( myString, '_',' ' );
You can use the replacement pattern which is also called substitution.
You can find graet info here:
http://msdn.microsoft.com/en-us/library/ewy2t5e0.aspx
Good luck
I have a string that I use for client side validation:
private const String regex = #"^(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([A-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$";
I use this string in my [RegularExpression(regex, ErrorMessage = "invalid")] attribute.
I know that the /i flag for a Javascript regex is used to make it case insensitive, but just tacking it on to the end of my regex (i.e. #"^....$/i" isn't working - the regex validation fails completely, regardless of what is entered (valid or not).
What am I missing?
I created this attribute which allows you to specify RegexOptions. EDIT: It also integrates with unobtrusive validation. The client will only obey RegexOptions.Multiline and RegexOptions.IgnoreCase since that is what JavaScript supports.
[RegularExpressionWithOptions(#".+#example\.com", RegexOptions = RegexOptions.IgnoreCase)]
C#
public class RegularExpressionWithOptionsAttribute : RegularExpressionAttribute, IClientValidatable
{
public RegularExpressionWithOptionsAttribute(string pattern) : base(pattern) { }
public RegexOptions RegexOptions { get; set; }
public override bool IsValid(object value)
{
if (string.IsNullOrEmpty(value as string))
return true;
return Regex.IsMatch(value as string, "^" + Pattern + "$", RegexOptions);
}
public IEnumerable<System.Web.Mvc.ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = FormatErrorMessage(metadata.DisplayName),
ValidationType = "regexwithoptions"
};
rule.ValidationParameters["pattern"] = Pattern;
string flags = "";
if ((RegexOptions & RegexOptions.Multiline) == RegexOptions.Multiline)
flags += "m";
if ((RegexOptions & RegexOptions.IgnoreCase) == RegexOptions.IgnoreCase)
flags += "i";
rule.ValidationParameters["flags"] = flags;
yield return rule;
}
}
JavaScript
(function ($) {
$.validator.unobtrusive.adapters.add("regexwithoptions", ["pattern", "flags"], function (options) {
options.messages['regexwithoptions'] = options.message;
options.rules['regexwithoptions'] = options.params;
});
$.validator.addMethod("regexwithoptions", function (value, element, params) {
var match;
if (this.optional(element)) {
return true;
}
var reg = new RegExp(params.pattern, params.flags);
match = reg.exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));
});
})(jQuery);
This article by Anthony Stevens helped me get this working: ASP.NET MVC 3 Unobtrusive Javascript Validation With Custom Validators
In C# you can inline some regex options. To specify the option to ignore case you would add (?i) to the beginning of your pattern. However, I am not sure how this would be treated by the RegularExpressionAttribute and if it handles translation for client-side. From my experience with ASP.NET's RegularExpressionValidator I doubt it; the regex should be vanilla enough to work for both engines.
In any case if it was valid it would look like this:
#"^(?i)(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([A-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$"
private const String regex = #"^(?:\b(?:\d{5}(?:\s*-\s*\d{5})?|([a-zA-Z]{2})\d{3}(?:\s*-\s*\1\d{3})?)(?:,\s*)?)+$";