/// <summary> /// Determine whether input is a valid IP address of the address families /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool IPAddress(this ValidatableValue<string> input, params System.Net.Sockets.AddressFamily[] family) { if (family == null || !family.Any()) { input.AddError("No AddressFamily specified"); return false; } IPAddress address; if (System.Net.IPAddress.TryParse(input.Value, out address)) { if (family.Contains(address.AddressFamily)) { return true; } input.AddError("AddressFamily doesn't match"); } else { input.AddError("Failed to parse IP address"); } return false; }
/// <summary> /// Indicates whether supplied input is either in ISBN-10 digit format or ISBN-13 digit format. /// </summary> /// <param name="input"></param> /// <param name="version">Valid options are: IsbnVersion.Ten, IsbnVersion.Thirteen or IsbnVersion.Any</param> /// <returns></returns> /// IsbnVersion public static bool Isbn(this ValidatableValue<string> inputVal, IsbnVersion version = IsbnVersion.Any) { var input = RemoveSpacesAndHyphens(inputVal.Value); switch (version) { case IsbnVersion.Any: if (!IsIsbn10(input) && !IsIsbn13(input)) { inputVal.AddError("Not ISBN 10 or 13"); } return inputVal.IsValid; case IsbnVersion.Thirteen: if (!IsIsbn13(input)) { inputVal.AddError("Not ISBN 13"); } return inputVal.IsValid; case IsbnVersion.Ten: if (!IsIsbn10(input)) { inputVal.AddError("Not ISBN 10"); } return inputVal.IsValid; } throw new ArgumentOutOfRangeException( "version", string.Format("Isbn version {0} is not supported.", version)); }
/// <summary> /// Indicates whether input is in correct format for a credit card number and is valid. /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool CreditCard(this ValidatableValue<string> inputV) { var input = inputV.Value.Replace(" ", ""); input = input.Replace("-", ""); if (!input.IsValid().Numeric()) { inputV.AddError("Contains invalid characters"); } else { var sumOfDigits = 0; var pos = 0; for (var i = input.Length - 1; i >= 0; i--) { var e = input[i]; if (e >= '0' && e <= '9') { var v = ((int)e - 48) * (pos % 2 == 0 ? 1 : 2); sumOfDigits += v / 10 + v % 10; pos++; } } if (sumOfDigits % 10 != 0) { inputV.AddError("Check sum not valid"); } } return inputV.IsValid; }
/// <summary> /// Banks the account. /// </summary> /// <param name="branchNumber">The combind branch/bank number. I.E. UK sort code</param> /// <returns></returns> public static bool BankAccount(this ValidatableValue<string> inputV, string branchNumber) { var errors = new List<ValidationResult>(); foreach (var l in inputV.Locale) { var validator = new ValidatableValue<string>(inputV.Value, l); if (validatorsWithBranch.ContainsKey(l)) { if (validatorsWithBranch[l](validator, branchNumber)) { //is valid no errors return true; } } else { validator.AddError($"Unable to validate banks for '{l}'"); } errors.AddRange(validator.Errors); } //lets add all the validation errors (if invalid to the source validatable) foreach (var r in errors) { inputV.AddError(r); } return inputV.IsValid; }
/// <summary> /// 把錯誤訊息記錄到IValidationDictionary的物件裡面 /// </summary> /// <param name="validationDictionary">儲存目前Validation結果的Dictionary</param> /// <param name="propertyErrors">要記錄到ValidationDictionary裡面的錯誤訊息</param> public static void AddValidationErrors(this IValidationDictionary validationDictionary, IValidationErrors propertyErrors) { foreach (var databaseValidationError in propertyErrors.Errors) { validationDictionary.AddError(databaseValidationError.PropertyName, databaseValidationError.PropertyExceptionMessage); } }
/// <summary> /// Determines whether the given phone number is a mobile phone number or not. Based on the current locale of the executing thread /// </summary> /// <param name="phoneNumber">The phone number to check.</param> /// <param name="exitCode">The exit code.</param> /// <returns> /// True if it is a mobile phone number, false otherwise. /// </returns> /// <remarks> /// Relies on locales that use specific blocks of numbers for mobile phone numbers. /// </remarks> public static bool MobilePhone(this ValidatableValue<string> phoneNumber, string exitCode) { if (!phoneNumber.Locale.Any(loc => IsLocalPhone(phoneNumber, loc, exitCode))) { phoneNumber.AddError("Not a recognised mobile phone number"); } return phoneNumber.IsValid; }
/// <summary> /// Indicates whether supplied input is either in ISBN-10 digit format or ISBN-13 digit format. /// </summary> /// <param name="input"></param> /// <param name="version">Valid options are: IsbnVersion.Ten, IsbnVersion.Thirteen or IsbnVersion.Any</param> /// <returns></returns> /// IsbnVersion public static bool BusinessIdentifierCode(this ValidatableValue<string> inputVal) { var val = inputVal.Value; if (!(val.Length == 8 || val.Length == 11)) { inputVal.AddError("Invalid length"); } if (val.Length >= 4) { var institutionCode = inputVal.Value.Substring(0, 4); if (institutionCode.Any(x => !Char.IsLetter(x))) { //must be made up of letters inputVal.AddError("Invalid Institution Code"); } } if (val.Length >= 6) { var countryCode = inputVal.Value.Substring(4, 2).ToUpperInvariant(); if (!Constants.CountryCodes.Codes.Contains(countryCode)) { inputVal.AddError("Invalid Country Code"); } } if (val.Length >= 8) { var locationCode = inputVal.Value.Substring(6, 2).ToUpperInvariant(); if (locationCode.Any(x => !Char.IsLetterOrDigit(x))) { //must be made up of letters inputVal.AddError("Invalid Location Code"); } } if (val.Length >= 11) { var branchCode = inputVal.Value.Substring(8, 3).ToUpperInvariant(); if (branchCode.Any(x => !Char.IsLetterOrDigit(x))) { //must be made up of letters inputVal.AddError("Invalid Branch Code"); } } return inputVal.IsValid; }
/// <summary> /// Determine whether input matches a valid email address. /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool Email(this ValidatableValue<string> input) { try { if (new MailAddress(input.Value).Address != input.Value) { input.AddError("Input doesn't match address part"); } return true; } catch (Exception ex) { input.AddError(ex.Message); } return false; }
/// <summary> /// Determine whether input matches a valid email address. /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool Email(this ValidatableValue<string> input) { try { var validationResult = IsValid(input.Value); if (validationResult != null) { input.AddError(validationResult); return false; } return true; } catch (Exception ex) { input.AddError(ex.Message); } return false; }
public static void AddIdentityResult(this IValidationErrorNotifier errors, IdentityResult result) { Contract.Requires(errors != null); Contract.Requires(result != null); if(result.Succeeded) return; foreach(var errorMessage in result.Errors) { errors.AddError(errorMessage); } }
/// <summary> /// Merge all error found in an application message into the current validation dictionary /// </summary> /// <param name="validationDictionary">instance of IValidationDictionary</param> /// <param name="executionResult">instance of IApplicationMessage</param> /// <param name="fromMessageCategory">look for error messages from this category</param> /// <returns></returns> public static IValidationDictionary Merge(this IValidationDictionary validationDictionary, ExecutionResult executionResult, MessageCategory fromMessageCategory = MessageCategory.BrokenBusinessRule) { if ((validationDictionary != null) && (executionResult != null) && !executionResult.IsSuccessFull) { var propertyName = executionResult[fromMessageCategory].PropertyName; executionResult[fromMessageCategory] .Messages .Each(errorMessage => validationDictionary.AddError(propertyName, errorMessage)); } return validationDictionary; }
/// <summary> /// Determine whether input is in lower case. /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool Lowercase(this ValidatableValue<string> input) { if (!input.IsValueSet || input.Value == null) { return true; } var val = input.Value; if (val != val.ToLower()) { input.AddError("Contains uppercase characters"); } return input.IsValid; }
/// <summary> /// Indicates whether input is in correct format for a number and is valid. /// </summary> /// <param name="input"></param> /// <returns></returns> public static bool Numeric(this ValidatableValue<string> inputValue) { var input = inputValue.Value; if (input == null) { inputValue.AddError("Null value"); return false; } int length = input.Length; if (length == 0) { inputValue.AddError("No characters"); return false; } int i = 0; if (input[0] == '-') { if (length == 1) { inputValue.AddError("Contains only '-'"); return false; } i = 1; } for (; i < length; i++) { char c = input[i]; if (c <= '/' || c >= ':') { inputValue.AddError("Contains out of range character"); return false; } } return true; }
public static bool Model(this ValidatableValue<object> input) { if (input.Value == null) { return false; } var context = new ValidationContext(input.Value); //context.MemberName = "Range"; var results = new List<ValidationResult>(); System.ComponentModel.DataAnnotations.Validator.TryValidateObject(input.Value, context, results, true); input.AddError(results); return input.IsValid; }
public static OperationOutcome AddError(this OperationOutcome outcome, Exception exception) { string message; if(exception is SparkException) message = exception.Message; else message = string.Format("{0}: {1}", exception.GetType().Name, exception.Message); outcome.AddError(message); // Don't add a stacktrace if this is an acceptable logical-level error if (!(exception is SparkException)) { var stackTrace = new OperationOutcome.OperationOutcomeIssueComponent(); stackTrace.Severity = OperationOutcome.IssueSeverity.Information; stackTrace.Diagnostics = exception.StackTrace; outcome.Issue.Add(stackTrace); } return outcome; }
/// <summary> /// Validates the bank account to as though its UK based /// </summary> /// <param name="inputV">The input v.</param> /// <param name="branchNumber">The branch number.</param> /// <returns></returns> public static bool UKBankAccount(this ValidatableValue<string> accountValidatable, string branchNumber) { Initilize(); //convertToInt to seed up validator range checks var cleanedBranchNumber = RemoveSpacesAndHyphens(branchNumber); if (cleanedBranchNumber.Length != 6) { accountValidatable.AddError("branchNumber must be exactly 6 digits long"); return accountValidatable.IsValid; } int integerBracnhNumber = 0; if (!int.TryParse(cleanedBranchNumber, out integerBracnhNumber)) { accountValidatable.AddError("branchNumber is in a invalid format"); } //lets run some account number/sortcodes var cleanedAccountNumber = RemoveSpacesAndHyphens(accountValidatable.Value); if (cleanedAccountNumber.Length < 8) { cleanedAccountNumber = cleanedAccountNumber.PadLeft(8, '0');//padded } if (cleanedAccountNumber.Length == 9) { //Santander (formerly Alliance & Leicester Commercial Bank plc) //we use the fist digit of the account as the last digit of the sortcode cleanedBranchNumber = cleanedBranchNumber.Substring(0, 5) + cleanedAccountNumber[0]; cleanedAccountNumber = cleanedAccountNumber.Substring(1, 8); } //if we have 10 digits then we actually have to perform the check twice becauseer there are 2 different ways to cut up an 8 digit number if (cleanedAccountNumber.Length == 10) { //this could be a 'National Westminster Bank plc' if so use last 8 var validatable = new ValidatableValue<string>(cleanedAccountNumber.Substring(2, 8)); UKBankAccount(validatable, cleanedBranchNumber); if (!validatable.IsValid) { //Co-Operative Bank plc last 8 validatable = new ValidatableValue<string>(cleanedAccountNumber.Substring(0, 8)); UKBankAccount(validatable, cleanedBranchNumber); } foreach (var e in validatable.Errors) { accountValidatable.AddError(e); } return accountValidatable.IsValid; } var combindAccountRef = cleanedBranchNumber + cleanedAccountNumber; var validator = validators.Where(x => x.CanValidate(integerBracnhNumber, combindAccountRef)); if (!validator.Any()) { //is valid we cant test it return accountValidatable.IsValid; } var firstTest = validator.First(); if (firstTest.Exception == 5) { //for exception 5 we need to swap out the sortcode and start again if (sortCodeSubstitutions.ContainsKey(cleanedBranchNumber)) { cleanedBranchNumber = sortCodeSubstitutions[cleanedBranchNumber]; integerBracnhNumber = int.Parse(cleanedBranchNumber); combindAccountRef = cleanedBranchNumber + cleanedAccountNumber; validator = validators.Where(x => x.CanValidate(integerBracnhNumber, combindAccountRef)); } } if (firstTest.Calculate(combindAccountRef)) { if (validator.Count() == 1 || new[] { 2, 9, 10, 11, 12, 13, 14 }.Contains(firstTest.Exception)) { return accountValidatable.IsValid; } else { if (validator.Skip(1).First().Calculate(combindAccountRef)) { return accountValidatable.IsValid; } } } else { var secondTest = validator.Skip(1).FirstOrDefault(); if (firstTest.Exception == 2) { combindAccountRef = "309634" + cleanedAccountNumber; secondTest = validators.FirstOrDefault(x => x.CanValidate(309634, combindAccountRef)); } if (new[] { 2, 9, 10, 11, 12, 13, 14 }.Contains(firstTest.Exception)) { if (secondTest?.Calculate(combindAccountRef) == true) { return accountValidatable.IsValid; } } } accountValidatable.AddError("Invalid account details"); return accountValidatable.IsValid; }
public static AjaxContinuation AddErrors(this AjaxContinuation ajaxContinuation, ValidationError[] validationErrors) { if (validationErrors == null) return ajaxContinuation; validationErrors.Each(x => ajaxContinuation.AddError(x)); return ajaxContinuation; }
public static IRoute AddError(this IRoute route, string errorMessage) { return route.AddError(new Error(errorMessage)); }
/// <summary> /// Indicates whether supplied input is either in ISBN-10 digit format or ISBN-13 digit format. /// </summary> /// <param name="input"></param> /// <param name="version">Valid options are: IsbnVersion.Ten, IsbnVersion.Thirteen or IsbnVersion.Any</param> /// <returns></returns> /// IsbnVersion public static bool Iban(this ValidatableValue<string> inputVal) { var val = inputVal.Value.ToUpper(); var countryCode = val.Trim().Substring(0, 2); var validator = _countryValidationLength.FirstOrDefault(x => x.CountryCode == countryCode); if (validator == null) { inputVal.AddError("Unrecognised country code"); return false; } return validator.Validate(inputVal); }
/// <summary> /// <paramref name="responseMessage"/>에 예외정보를 추가합니다. /// </summary> public static void ReportError(this ResponseMessage responseMessage, Exception ex) { if(ex == null) return; responseMessage.AddError(ex); if(log.IsWarnEnabled) log.WarnException("작업처리 중 예외가 발생하여, 응답 메시지에 예외정보를 추가했습니다.", ex); }
public static AjaxContinuation AddError(this AjaxContinuation ajaxContinuation, ValidationError validationError) { if (validationError == null) return ajaxContinuation; ajaxContinuation.AddError(new AjaxError{field = validationError.field, message = validationError.message}); return ajaxContinuation; }