public void Test_ValidEmailSuccess() { #region Arrange string expectedStatusCode = "OK"; int userId = 3; #endregion #region acts GetUserByIdRequest getUsersRequest = new GetUserByIdRequest(userId); IRestResponse <dynamic> response = getUsersRequest.ExecuteRequest(); string emailResponse = response.Data.email.ToString(); #endregion #region Asserts bool isValidEmail = RegexHelpers.IsValidEmail(emailResponse); Assert.Multiple(() => { Assert.AreEqual(expectedStatusCode, response.StatusCode.ToString()); Assert.True(isValidEmail); //Etc }); #endregion }
private bool IsPropertyDefinied(JSchema schema, string propertyName) { if (schema._properties != null && schema._properties.ContainsKey(propertyName)) { return(true); } if (schema._patternProperties != null) { foreach (PatternSchema patternSchema in schema.GetPatternSchemas()) { if (patternSchema.TryGetPatternRegex( #if !(NET35 || NET40) Context.Validator.RegexMatchTimeout, #endif out Regex regex, out string _)) { if (RegexHelpers.IsMatch(regex, patternSchema.Pattern, propertyName)) { return(true); } } } } return(false); }
internal bool TryGetPatternRegex(out Regex regex, out string errorMessage) { bool result = RegexHelpers.TryGetPatternRegex(_pattern, ref _patternRegex, ref _patternError); regex = _patternRegex; errorMessage = _patternError; return(result); }
public QueryClass(string pInput) { var returned = RegexHelpers.SplitKeyValue(pInput); //just returns a string like "Make = Honda" into three parts if (returned != null) { FieldName = returned.Item1; Operator = returned.Item2; Value = returned.Item3; } }
public void TryGetPatternRegex_ECMARegexPattern_Success() { string pattern = @"^-?(?:[1-9]\d{3}(-?)(?:(?:0[1-9]|1[0-2])\1(?:0[1-9]|1\d|2[0-8])|(?:0[13-9]|1[0-2])\1(?:29|30)|(?:0[13578]|1[02])(?:\1)31|00[1-9]|0[1-9]\d|[12]\d{2}|3(?:[0-5]\d|6[0-5]))|(?:[1-9]\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)(?:(-?)02(?:\2)29|-?366))(?:Z|[+-][01]\d(?:\3[0-5]\d)?)$"; Regex regex1 = null; string errorMessage1 = null; bool result1 = RegexHelpers.TryGetPatternRegex(pattern, null, ref regex1, ref errorMessage1); Assert.AreEqual(true, result1); Assert.AreEqual(RegexOptions.ECMAScript, regex1.Options); }
public static bool IsEmailAddressPartOfHostname(string emailAddress, params string[] hostnames) { if (string.IsNullOrEmpty(emailAddress)) { return(false); } var pattern = $"\\w+@({hostnames.Join("|")})\\b"; var expr = RegexHelpers.Create(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline); return(expr.IsMatch(emailAddress)); }
private void menuFindNext_Click(object sender, EventArgs e) { // if Find & Replace dialog is open, we'll use RegexHelpers.FindNext to find the next occurrence with the given options if (_findReplace == null || !_findReplace.Created) { return; } var currentTxtEditor = GetCurrentNocTextEditor(); if (currentTxtEditor != null) { RegexHelpers.FindNext(_findReplace.txtFindWhat.Text, _findReplace.chbCaseSensitive.Checked, currentTxtEditor, _findReplace.chbRxp.Checked); } }
public void TryGetPatternRegex_MatchTimeout_Null() { Regex regex1 = null; string errorMessage1 = null; RegexHelpers.TryGetPatternRegex("[abc]", null, ref regex1, ref errorMessage1); Assert.IsNotNull(regex1); Regex regex2 = regex1; string errorMessage2 = errorMessage1; RegexHelpers.TryGetPatternRegex("[abc]", null, ref regex2, ref errorMessage2); Assert.AreEqual(regex1, regex2); }
public void Test_EmailInvalidoComSucesso() { #region Parameters string email = "email@valido"; #endregion #region Acoes bool isValidEmail = RegexHelpers.IsValidEmail(email); #endregion #region Asserts Assert.IsFalse(isValidEmail); #endregion }
public void TryGetPatternRegex_MatchTimeout_Defined() { TimeSpan matchTimeout = TimeSpan.FromSeconds(1); Regex regex1 = null; string errorMessage1 = null; RegexHelpers.TryGetPatternRegex("[abc]", matchTimeout, ref regex1, ref errorMessage1); Assert.IsNotNull(regex1); Regex regex2 = regex1; string errorMessage2 = errorMessage1; RegexHelpers.TryGetPatternRegex("[abc]", matchTimeout, ref regex2, ref errorMessage2); Assert.AreEqual(regex1, regex2); }
internal static bool ValidateString(SchemaScope scope, JSchema schema, string value) { if (!TestType(scope, schema, JSchemaType.String, value)) { return(false); } if (schema.MaximumLength != null || schema.MinimumLength != null) { // want to test the character length and ignore unicode surrogates StringInfo stringInfo = new StringInfo(value); int textLength = stringInfo.LengthInTextElements; if (schema.MaximumLength != null && textLength > schema.MaximumLength) { scope.RaiseError($"String '{value}' exceeds maximum length of {schema.MaximumLength}.", ErrorType.MaximumLength, schema, value, null); } if (schema.MinimumLength != null && textLength < schema.MinimumLength) { scope.RaiseError($"String '{value}' is less than minimum length of {schema.MinimumLength}.", ErrorType.MinimumLength, schema, value, null); } } if (schema.Pattern != null) { if (schema.TryGetPatternRegex( #if !(NET35 || NET40) scope.Context.Validator.RegexMatchTimeout, #endif out Regex regex, out string errorMessage)) { if (!RegexHelpers.IsMatch(regex, schema.Pattern, value)) { scope.RaiseError($"String '{value}' does not match regex pattern '{schema.Pattern}'.", ErrorType.Pattern, schema, value, null); } } else { scope.RaiseError($"Could not validate string with regex pattern '{schema.Pattern}'. There was an error parsing the regex: {errorMessage}", ErrorType.Pattern, schema, value, null); } }
internal bool TryGetPatternRegex( #if !(NET35 || NET40) TimeSpan?matchTimeout, #endif out Regex regex, out string errorMessage) { bool result = RegexHelpers.TryGetPatternRegex( _pattern, #if !(NET35 || NET40) matchTimeout, #endif ref _patternRegex, ref _patternError); regex = _patternRegex; errorMessage = _patternError; return(result); }
internal bool TryGetPatternRegex( #if !(NET35 || NET40) TimeSpan?matchTimeout, #endif [NotNullWhen(true)] out Regex?regex, [NotNullWhen(false)] out string?errorMessage) { bool result = RegexHelpers.TryGetPatternRegex( _pattern, #if !(NET35 || NET40) matchTimeout, #endif ref _patternRegex, ref _patternError); regex = _patternRegex; errorMessage = _patternError; return(result); }
static void RegexMatch(string data, string pattern, RegexOptions options, bool showHelp, bool matchAll = false) { if (showHelp) { List <Parameter> parms = new List <Parameter> { new Parameter { Key = "file", Type = typeof(string), HelpText = "Path to file" }, new Parameter { Key = "pattern", Type = typeof(string), HelpText = "Match pattern" }, new Parameter { Key = "[options]", Type = typeof(string), HelpText = "RegexOptions. Default: default behavior" } }; ConsoleColor defaultColor = Console.ForegroundColor; Console_WriteLine($"Parameter options for {(matchAll ? "RegexMatches" : "RegexMatch")} action:\r\n", ConsoleColor.Green); WriteMethodParametersHelp(parms); Console.ForegroundColor = defaultColor; } else if (!string.IsNullOrWhiteSpace(pattern)) { if (matchAll) { Console.WriteLine($"Executing RegexMatches on file.\r\n"); MatchCollection mc = RegexHelpers.Matches(data, pattern, options, Regex.InfiniteMatchTimeout); foreach (Match m in mc) { Console.WriteLine(m.ToString()); } } else { Console.WriteLine($"Executing RegexMatch on file.\r\n"); Match m = RegexHelpers.Match(data, pattern, options, Regex.InfiniteMatchTimeout); Console.WriteLine(m.ToString()); } } }
public static async Task <Poll> GetPollAsync(HttpClient httpClient, string id) { var responseMessage = await httpClient.GetAsync($"http://www.strawpoll.me/embed_1/{id}"); var decode = WebUtility.HtmlDecode(await responseMessage.Content.ReadAsStringAsync()); string title = RegexHelpers.GetValue(decode, "<h2>(.+)<\\/h2>").Groups[1].Value; string token = RegexHelpers.GetValue(decode, "name=\"security-token\" type=\"hidden\" value=\"(.+)\"").Groups[1].Value; IEnumerable <Vote> votes = GetVotes(); IEnumerable <Vote> GetVotes() { var matches = RegexHelpers.GetValues(decode, "<input type=\"radio\"\\s+ name=\"options\"\\s+ value=\"(.+)\"\\s+ id=\"field-options-.+\" \\/>\\s+<label title=\"\"\\s+ id=\"field-options-.+\" for=\"field-options-.+\" ><span>(.+)<\\/span><\\/label>\r\n"); foreach (Match match in matches) { yield return(new Vote(match.Groups[1].Value, match.Groups[2].Value)); } } return(new Poll(title, votes, token)); }
public ActionResult InformationCard(UserViewModel userViewModel) { #region var name = userViewModel.Name.SetNull(); var phone = userViewModel.Phone.SetNull(); var usercard = userViewModel.UserCard.SetNull(); if (string.IsNullOrEmpty(name)) { ModelState.AddModelError("name", "姓名不能为空"); return(View(userViewModel)); } if (!RegexHelpers.IsCNMobileNum(phone)) { ModelState.AddModelError("phone", "手机号格式错误"); return(View(userViewModel)); } if (!RegexHelpers.IsUserCard(usercard)) { ModelState.AddModelError("usercard", "身份证号格式错误"); return(View(userViewModel)); } #endregion if (ModelState.IsValid) { var shopCarViewModel = Session["Car"] as ShopCarViewModel; if (shopCarViewModel != null && shopCarViewModel.CardInfo.Count != 0) { userViewModel.SumPrice = shopCarViewModel.UserInfo.SumPrice; shopCarViewModel.UserInfo = userViewModel; Session["Car"] = shopCarViewModel; } return(RedirectToAction("CheckInfoCard")); } return(View(userViewModel)); }
protected override bool EvaluateTokenCore(JsonToken token, object value, int depth) { int relativeDepth = depth - InitialDepth; if (relativeDepth == 0) { EnsureEnum(token, value); switch (token) { case JsonToken.StartObject: EnsureValid(value); TestType(Schema, JSchemaType.Object); return(false); case JsonToken.EndObject: ValidateConditionalChildren(token, value, depth); if (!Schema._required.IsNullOrEmpty() && _requiredProperties.Count > 0) { //capture required properties at current depth as we may clear _requiredProperties later on List <string> capturedRequiredProperties = _requiredProperties.ToList(); RaiseError($"Required properties are missing from object: {StringHelpers.Join(", ", capturedRequiredProperties)}.", ErrorType.Required, Schema, capturedRequiredProperties, null); } if (Schema.MaximumProperties != null && _propertyCount > Schema.MaximumProperties) { RaiseError($"Object property count {_propertyCount} exceeds maximum count of {Schema.MaximumProperties}.", ErrorType.MaximumProperties, Schema, _propertyCount, null); } if (Schema.MinimumProperties != null && _propertyCount < Schema.MinimumProperties) { RaiseError($"Object property count {_propertyCount} is less than minimum count of {Schema.MinimumProperties}.", ErrorType.MinimumProperties, Schema, _propertyCount, null); } if (!Schema._dependencies.IsNullOrEmpty()) { foreach (string readProperty in _readProperties) { if (Schema._dependencies.TryGetValue(readProperty, out object dependency)) { if (dependency is List <string> requiredProperties) { if (!requiredProperties.All(r => _readProperties.Contains(r))) { IEnumerable <string> missingRequiredProperties = requiredProperties.Where(r => !_readProperties.Contains(r)); IFormattable message = $"Dependencies for property '{readProperty}' failed. Missing required keys: {StringHelpers.Join(", ", missingRequiredProperties)}."; RaiseError(message, ErrorType.Dependencies, Schema, readProperty, null); } } else { SchemaScope dependencyScope = _dependencyScopes[readProperty]; if (dependencyScope.Context.HasErrors) { IFormattable message = $"Dependencies for property '{readProperty}' failed."; RaiseError(message, ErrorType.Dependencies, Schema, readProperty, ((ConditionalContext)dependencyScope.Context).Errors); } } } } } if (Schema._patternProperties != null) { foreach (PatternSchema patternSchema in Schema.GetPatternSchemas()) { if (!patternSchema.TryGetPatternRegex( #if !(NET35 || NET40) Context.Validator.RegexMatchTimeout, #endif out Regex _, out string errorMessage)) { RaiseError($"Could not test property names with regex pattern '{patternSchema.Pattern}'. There was an error parsing the regex: {errorMessage}", ErrorType.PatternProperties, Schema, patternSchema.Pattern, null); } } } return(true); default: throw new InvalidOperationException("Unexpected token when evaluating object: " + token); } } if (relativeDepth == 1) { if (token == JsonToken.PropertyName) { _propertyCount++; _currentPropertyName = (string)value; if (!Schema._required.IsNullOrEmpty()) { _requiredProperties.Remove(_currentPropertyName); } if (!Schema._dependencies.IsNullOrEmpty()) { _readProperties.Add(_currentPropertyName); } if (Schema._propertyNames != null) { CreateScopesAndEvaluateToken(token, value, depth, Schema._propertyNames); } if (!Schema.AllowAdditionalProperties) { if (!IsPropertyDefinied(Schema, _currentPropertyName)) { IFormattable message = $"Property '{_currentPropertyName}' has not been defined and the schema does not allow additional properties."; RaiseError(message, ErrorType.AdditionalProperties, Schema, _currentPropertyName, null); } } } else { if (JsonTokenHelpers.IsPrimitiveOrStartToken(token)) { bool matched = false; if (Schema._properties != null) { if (Schema._properties.TryGetValue(_currentPropertyName, out JSchema propertySchema)) { CreateScopesAndEvaluateToken(token, value, depth, propertySchema); matched = true; } } if (Schema._patternProperties != null) { foreach (PatternSchema patternProperty in Schema.GetPatternSchemas()) { if (patternProperty.TryGetPatternRegex( #if !(NET35 || NET40) Context.Validator.RegexMatchTimeout, #endif out Regex regex, out string _)) { if (RegexHelpers.IsMatch(regex, patternProperty.Pattern, _currentPropertyName)) { CreateScopesAndEvaluateToken(token, value, depth, patternProperty.Schema); matched = true; } } } } if (!matched) { if (Schema.AllowAdditionalProperties && Schema.AdditionalProperties != null) { CreateScopesAndEvaluateToken(token, value, depth, Schema.AdditionalProperties); } } } } } return(false); }
private void btnReplaceAll_Click(object sender, EventArgs e) { // use Tools.ReplaceAll to replace all occurrences of a string RegexHelpers.ReplaceAll(txtFindWhat.Text, txtReplaceWith.Text, chbCaseSensitive.Checked, _currentTextBox, chbRxp.Checked); }
protected override bool EvaluateTokenCore(JsonToken token, object?value, int depth) { int relativeDepth = depth - InitialDepth; if (relativeDepth == 0) { EnsureEnum(token, value); switch (token) { case JsonToken.StartObject: EnsureValid(value); TestType(Schema, JSchemaType.Object); return(false); case JsonToken.EndObject: ValidateConditionalChildren(token, value, depth); if (!Schema._required.IsNullOrEmpty() && _requiredProperties !.Count > 0) { //capture required properties at current depth as we may clear _requiredProperties later on List <string> capturedRequiredProperties = _requiredProperties.ToList(); RaiseError($"Required properties are missing from object: {StringHelpers.Join(", ", capturedRequiredProperties)}.", ErrorType.Required, Schema, capturedRequiredProperties, null); } if (Schema.MaximumProperties != null && _propertyCount > Schema.MaximumProperties) { RaiseError($"Object property count {_propertyCount} exceeds maximum count of {Schema.MaximumProperties}.", ErrorType.MaximumProperties, Schema, _propertyCount, null); } if (Schema.MinimumProperties != null && _propertyCount < Schema.MinimumProperties) { RaiseError($"Object property count {_propertyCount} is less than minimum count of {Schema.MinimumProperties}.", ErrorType.MinimumProperties, Schema, _propertyCount, null); } if (HasDependencies()) { foreach (string readProperty in _readProperties !) { object? dependency = null; IList <string>?requiredProperties = null; if (Schema._dependencies?.TryGetValue(readProperty, out dependency) ?? false) { requiredProperties = dependency as IList <string>; if (requiredProperties != null) { ValidateDependantProperties(readProperty, requiredProperties); } else { ValidateDependantSchema(readProperty); } } if (Schema._dependentRequired?.TryGetValue(readProperty, out requiredProperties) ?? false) { ValidateDependantProperties(readProperty, requiredProperties !); } if (Schema._dependentSchemas?.TryGetValue(readProperty, out _) ?? false) { ValidateDependantSchema(readProperty); } } } // Evaluate after dependency schemas have been validated if (!_unevaluatedScopes.IsNullOrEmpty()) { foreach (KeyValuePair <string, UnevaluatedContext> item in _unevaluatedScopes) { if (!item.Value.Evaluated) { IFormattable message = $"Property '{item.Key}' has not been successfully evaluated and the schema does not allow unevaluated properties."; RaiseError(message, ErrorType.UnevaluatedProperties, Schema, item.Key, item.Value.SchemaScope.GetValidationErrors()); } } } if (Schema._patternProperties != null) { foreach (PatternSchema patternSchema in Schema.GetPatternSchemas()) { if (!patternSchema.TryGetPatternRegex( #if !(NET35 || NET40) Context.Validator.RegexMatchTimeout, #endif out Regex? _, out string?errorMessage)) { RaiseError($"Could not test property names with regex pattern '{patternSchema.Pattern}'. There was an error parsing the regex: {errorMessage}", ErrorType.PatternProperties, Schema, patternSchema.Pattern, null); } } } return(true); default: throw new InvalidOperationException("Unexpected token when evaluating object: " + token); } } if (relativeDepth == 1) { if (token == JsonToken.PropertyName) { _propertyCount++; _currentPropertyName = (string)value !; if (!Schema._required.IsNullOrEmpty()) { _requiredProperties !.Remove(_currentPropertyName); } if (HasDependencies()) { _readProperties !.Add(_currentPropertyName); } if (Schema._propertyNames != null) { CreateScopesAndEvaluateToken(token, value, depth, Schema._propertyNames); } if (!Schema.AllowAdditionalProperties) { if (!IsPropertyDefined(Schema, _currentPropertyName)) { IFormattable message = $"Property '{_currentPropertyName}' has not been defined and the schema does not allow additional properties."; RaiseError(message, ErrorType.AdditionalProperties, Schema, _currentPropertyName, null); } } } else { ValidationUtils.Assert(_currentPropertyName != null); if (JsonTokenHelpers.IsPrimitiveOrStartToken(token)) { bool matched = false; if (Schema._properties != null) { if (Schema._properties.TryGetValue(_currentPropertyName, out JSchema propertySchema)) { CreateScopesAndEvaluateToken(token, value, depth, propertySchema); matched = true; } } if (Schema._patternProperties != null) { foreach (PatternSchema patternProperty in Schema.GetPatternSchemas()) { if (patternProperty.TryGetPatternRegex( #if !(NET35 || NET40) Context.Validator.RegexMatchTimeout, #endif out Regex? regex, out string?_)) { if (RegexHelpers.IsMatch(regex, patternProperty.Pattern, _currentPropertyName)) { CreateScopesAndEvaluateToken(token, value, depth, patternProperty.Schema); matched = true; } } } } if (!matched) { if (Schema.AllowAdditionalProperties && Schema.AdditionalProperties != null) { CreateScopesAndEvaluateToken(token, value, depth, Schema.AdditionalProperties); } if (ShouldValidateUnevaluated()) { _unevaluatedScopes ![_currentPropertyName] = Schema.UnevaluatedProperties != null
private void btnReplace_Click(object sender, EventArgs e) { // use Tools.Replace to replace text with the given options RegexHelpers.Replace(txtFindWhat.Text, txtReplaceWith.Text, chbCaseSensitive.Checked, _currentTextBox, chbRxp.Checked); }
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)] //清除缓存 public JsonResult IsPhone(string phone) { var valid = RegexHelpers.IsCNMobileNum(phone); return(Json(valid, JsonRequestBehavior.AllowGet)); }
public ActionResult InformationTicket(UserViewModel userViewModel) { #region var name = userViewModel.Name.SetNull(); var phone = userViewModel.Phone.SetNull(); var usercard = userViewModel.UserCard.SetNull(); var goDate = userViewModel.GoDate; if (string.IsNullOrEmpty(name)) { ModelState.AddModelError("name", "姓名不能为空"); return(View(userViewModel)); } if (!RegexHelpers.IsCNMobileNum(phone)) { ModelState.AddModelError("phone", "手机号格式错误"); return(View(userViewModel)); } if (!RegexHelpers.IsUserCard(usercard)) { ModelState.AddModelError("usercard", "身份证号格式错误"); return(View(userViewModel)); } try { var date = Convert.ToDateTime(goDate); if (date.Date < DateTime.Now.Date) { ModelState.AddModelError("goDate", "请选择正确的日期"); return(View(userViewModel)); } if (date.Date == DateTime.Now.Date) { if (DateTime.Now.Hour >= 8) { ModelState.AddModelError("goDate", "8点后不能预定当天的票"); return(View(userViewModel)); } } } catch { ModelState.AddModelError("goDate", "请选择正确的日期"); return(View(userViewModel)); } #endregion Ticket if (ModelState.IsValid) { var shopCarViewModel = Session["Car"] as ShopCarViewModel; if (shopCarViewModel != null && shopCarViewModel.TicketInfo.Count != 0) { userViewModel.SumPrice = shopCarViewModel.UserInfo.SumPrice; shopCarViewModel.UserInfo = userViewModel; Session["Car"] = shopCarViewModel; } return(RedirectToAction("CheckInfoTicket")); } return(View(userViewModel)); }
public JsonResult IsUserCard(string userCard) { var valid = RegexHelpers.IsIDCard(userCard); return(Json(valid, JsonRequestBehavior.AllowGet)); }
/// <summary> /// Initializes a new instance of the <see cref="WildcardNamePattern"/> class. /// </summary> /// <param name="pattern">The wildcard pattern to use.</param> public WildcardNamePattern(string pattern) { Pattern = pattern ?? throw new ArgumentNullException(nameof(pattern)); Regex = RegexHelpers.FromWildcardExpression(pattern); }
private void btnFindNext_Click(object sender, EventArgs e) { // use Tools.FindNext to search for text with the given options RegexHelpers.FindNext(txtFindWhat.Text, chbCaseSensitive.Checked, _currentTextBox, chbRxp.Checked); }