// ******************************************************************* // Public methods. // ******************************************************************* #region Public methods /// <summary> /// This method determines whether the specified value of the object is /// valid, or not. /// </summary> /// <param name="value">The value of the object to validate.</param> /// <returns>true if the specified value is valid; false otherwise.</returns> public override bool IsValid( object value ) { // Validate the parameters before attempting to use them. Guard.Instance().ThrowIfNull(value, nameof(value)); var phoneAttribute = new PhoneAttribute(); // Validate based on the property type. if (value is IEnumerable <string> ) { var sequence = value as IEnumerable <string>; return(sequence != null && sequence.All(phone => phoneAttribute.IsValid(phone))); } else if (value is string) { var list = (value as string).Split(';'); return(list != null && list.All(phone => phoneAttribute.IsValid(phone))); } else { base.ErrorMessage = $"The property type: '{value.GetType().Name}' can't be validated"; return(false); } }
private SubmitStates ValidateSubmission(Submission submission) { //Domainside validation, ensures that validation could be left //out on the client side if (!codeStorage.CheckCode(submission.SerialNumber)) { return(SubmitStates.InvalidCode); } EmailAddressAttribute emailValidator = new EmailAddressAttribute(); PhoneAttribute phoneValidator = new PhoneAttribute(); if (submission.FirstName == "" || submission.SurName == "") { return(SubmitStates.InvalidInformation); } if (!emailValidator.IsValid(submission.EmailAdress)) { return(SubmitStates.InvalidInformation); } if (!phoneValidator.IsValid(submission.PhoneNumber)) { return(SubmitStates.InvalidInformation); } if (submission.Birthday.Equals(default(DateTime))) { return(SubmitStates.InvalidInformation); } return(SubmitStates.Success); }
public static PhoneAttribute CreatePhoneAttribute(string errorMessage = null) { var returnValue = new PhoneAttribute(); UpdateErrorMessage(returnValue, errorMessage); return(returnValue); }
public IActionResult CreateVerificationCode(string phone) { var attr = new PhoneAttribute(); if (!attr.IsValid(phone)) { return(Failed(ErrorCode.FormatError, "invalid phone number")); } var biz = new AccountBiz(); var code = biz.CreateVerificationCode(phone, VerificationExpires); var parameters = new[] { code.ToString(), VerificationExpires.ToString() }; var success = SMHelper.Send(phone, parameters, VerificationTemplate); // 此处的模板ID和参数需要与腾讯上的短信模板匹配 if (!success) { return(Failed(ErrorCode.Unknown, "验证码发送失败")); } var dto = new CreateVerificationCodeResponseDto { // Code = code, Minutes = VerificationExpires }; return(Success(dto)); }
public static void DataType_CustomDataType_ReturnsExpected() { var attribute = new PhoneAttribute(); Assert.Equal(DataType.PhoneNumber, attribute.DataType); Assert.Null(attribute.CustomDataType); }
/** +----------------------------------------+----------------+----------------+ | condition | valid class | invalid class | +----------------------------------------+----+-----------+----+-----------+ | lenght t of phone | 01 | t == 14 | 02 | t <> 14 | +----------------------------------------+----+-----------+----+-----------+ | character [0] is parentesis | 03 | yes | 04 | nope | +----------------------------------------+----+-----------+----+-----------+ | characters [1..2] are numeric | 05 | yes | 06 | nope | +----------------------------------------+----+-----------+----+-----------+ | character [3] is parentesis | 07 | yes | 08 | nope | +----------------------------------------+----+-----------+----+-----------+ | character [4] is a blank-space | 09 | yes | 10 | nope | +----------------------------------------+----+-----------+----+-----------+ | characters [5..8] are numeric | 11 | yes | 12 | nope | +----------------------------------------+----+-----------+----+-----------+ | character [9] are a dash | 13 | yes | 14 | nope | +----------------------------------------+----+-----------+----+-----------+ | characters [10..13] are numeric | 15 | yes | 16 | nope | +----------------------------------------+----+-----------+----+-----------+ **/ public void TestPhone(string phone, bool expected) { var attribute = new PhoneAttribute(); var actual = attribute.IsValid(phone); Assert.AreEqual(expected, actual); }
public async Task <IActionResult> SaveChanges(int appId, int offerId, string email, string phone, IFormFile file) { var application = _applicationData.FindById(appId); if (application == null) { return(View("NotFound")); } string uploadedUri = null; if (file != null) { var uploadSuccess = false; using (var stream = file.OpenReadStream()) { (uploadSuccess, uploadedUri) = await BlobStorageService.UploadToBlob(file.FileName, _configuration["storageconnectionstring"], null, stream); } if (uploadSuccess) { application.CvFile = uploadedUri; } } PhoneAttribute phoneAttr = new PhoneAttribute(); bool phoneValid = phoneAttr.IsValid(phone); EmailAddressAttribute emailAttr = new EmailAddressAttribute(); bool emailValid = emailAttr.IsValid(email); bool emailFree = !_jobOfferData.CheckIfEmailIsTaken(email, offerId); if (email == application.CommunicationEmail) { emailFree = true; } bool success = false; if (phoneValid && emailValid && emailFree) { application.Phone = phone; application.CommunicationEmail = email; _applicationData.Update(application); _applicationData.Commit(); success = true; } var result = Json(new { success, phoneValid, emailValid, emailFree, uploadedUri }); System.Threading.Thread.Sleep(700); return(result); }
public override bool IsValid(object value) { var phone = new PhoneAttribute(); //return true when the value is null or empty //return original IsValid value only when value is not null or empty return(value == null || string.IsNullOrEmpty(Convert.ToString(value)) || phone.IsValid(value)); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { var phone = new PhoneAttribute(); if (!phone.IsValid(value)) { return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName))); } return(null); }
/// <summary> /// Adds a PhoneAttribute. /// </summary> /// <param name="errMsg">Gets or sets an error message to associate with a validation control if validation fails.</param> /// <returns></returns> public BaValidatorList Phone(string errMsg = null) { var att = new PhoneAttribute(); if (errMsg != null) { att.ErrorMessage = errMsg; } Add(att); return(this); }
public void IsValid() { var sla = new PhoneAttribute(); Assert.IsTrue(sla.IsValid(null), "#A1-1"); Assert.IsFalse(sla.IsValid(String.Empty), "#A1-2"); Assert.IsFalse(sla.IsValid("string"), "#A1-3"); Assert.IsTrue(sla.IsValid("1-800-642-7676"), "#A1-4"); Assert.IsTrue(sla.IsValid("+86-21-96081318"), "#A1-5"); Assert.IsFalse(sla.IsValid(true), "#A1-6"); Assert.IsFalse(sla.IsValid(DateTime.Now), "#A1-7"); }
private string BuildValidationWithPhoneAttribute(PhoneAttribute phoneAttribute, string propertyName) { Type type = typeof(PhoneAttribute); FieldInfo info = type.GetField("_regex", BindingFlags.NonPublic | BindingFlags.Static); var value = info.GetValue(null); return (string.Format( @"model['{0}'].extend({{ pattern: {{ message: '{2}', params: /{1}/ }} }});", propertyName, @"^((8|\+7)-?)?\(?\d{3}\)?-?\d{1}-?\d{1}-?\d{1}-?\d{1}-?\d{1}-?\d{1}-?\d{1}?$", phoneAttribute.LocalizableError())); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (ignoreEmpty && (value == null || value.ToString() == string.Empty)) { return(ValidationResult.Success); } var result = new PhoneAttribute(); var errorMessage = string.IsNullOrEmpty(this.ErrorMessage) ? $"Invalid phone number." : this.ErrorMessage; result.ErrorMessage = errorMessage; return(result.GetValidationResult(value, validationContext)); }
public static void Validate_invalid_phone_numbers() { var attribute = new PhoneAttribute(); Assert.False(attribute.IsValid("(9999) 999-99-99")); Assert.False(attribute.IsValid("(999) 9999-99-99")); Assert.False(attribute.IsValid("(999) 999-999-99")); Assert.False(attribute.IsValid("(999) 999-99-999")); Assert.False(attribute.IsValid("9999-99-99")); Assert.False(attribute.IsValid("999-999-99")); Assert.False(attribute.IsValid("999-99-999")); Assert.False(attribute.IsValid("999-99")); Assert.False(attribute.IsValid("99-999")); }
public static void Validate_successful_for_valid_phone_numbers() { var attribute = new PhoneAttribute(); Assert.True(attribute.IsValid("(999) 999-99-99")); Assert.True(attribute.IsValid("(999) 9999999")); Assert.True(attribute.IsValid("(999)9999999")); Assert.True(attribute.IsValid("9999999999")); Assert.True(attribute.IsValid("999-99-99")); Assert.True(attribute.IsValid("999-9999")); Assert.True(attribute.IsValid("99999-99")); Assert.True(attribute.IsValid("9999999")); Assert.True(attribute.IsValid("99-99")); Assert.True(attribute.IsValid("9999")); }
public static PhoneAttribute CreatePhoneAttribute(this XElement annotation) { const string NAME = "Phone"; string name = annotation.Attribute(SchemaVocab.Name).Value; if (name != NAME) { throw new ArgumentException(string.Format(SchemaMessages.ExpectedBut, NAME, name)); } PhoneAttribute attribute = new PhoneAttribute(); FillValidationAttribute(attribute, annotation); return(attribute); }
protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value == null) { return(ValidationResult.Success); } var phoneNumberValidator = new PhoneAttribute(); var phoneNumbers = (string[])value; foreach (var phoneNumber in phoneNumbers) { if (!phoneNumberValidator.IsValid(phoneNumber)) { return(new ValidationResult(GetErrorMessage(phoneNumber))); } } return(ValidationResult.Success); }
/// <summary> /// Validity check /// 有效性检查 /// </summary> /// <param name="value">Input value</param> /// <returns>Result</returns> public override bool IsValid(object?value) { if (value == null) { return(true); } if (value is not string valueAsString) { return(false); } if (valueAsString.Contains('@')) { var email = new EmailAddressAttribute(); return(email.IsValid(value)); } else { var phone = new PhoneAttribute(); return(phone.IsValid(value)); } }
public ValidPhonesAttribute() { _phoneAttribute = new PhoneAttribute(); }
public PhoneValidationRule(PhoneAttribute attribute) : base("Phone", attribute) { }
/// <summary> /// Tries to convert the given value to the given format /// </summary> /// <param name="dataType">The data type of the given value</param> /// <param name="value">The value to type check</param> /// <returns>True of successful, otherwise throws exception</returns> private bool TryDataConversion(DataDescriptor descriptor, object data) { // Gaurd against null reference if (data == null) { throw new NullReferenceException(); } var value = data.ToString(); switch (descriptor.DataType) { case "bool": Convert <bool>(value); break; case "date-time": Convert <DateTimeOffset>(value); break; case "double": Convert <double>(value); break; case "email": Convert <string>(value); var emailValidator = new EmailAddressAttribute(); return(emailValidator.IsValid(value)); case "int32": Convert <int>(value); break; case "int64": Convert <long>(value); break; case "guid": Convert <Guid>(value); break; case "phone": Convert <string>(value); var phoneValidator = new PhoneAttribute(); return(phoneValidator.IsValid(value)); case "string": Convert <string>(value); if (!string.IsNullOrEmpty(descriptor.Pattern)) { var regexValidator = new RegularExpressionAttribute(descriptor.Pattern); return(regexValidator.IsValid(value)); } break; case "time-span": Convert <TimeSpan>(value); break; default: // Log error throw new NotImplementedException(string.Format("The format: {0} with value: {1} has no corresponding cast", descriptor.DataType, value)); } return(true); }
private static void ApplyPhoneAttribute(OpenApiSchema schema, PhoneAttribute phoneAttribute) { schema.Format = "tel"; }
static PhoneNumber() { _phoneValidator = new PhoneAttribute(); }
/// <summary> /// This method validates the contents of the main body of input text based on which type of message is being input. The method MessageHeaderInputValidation() /// determines what type of message is being input then changes a boolean value based on the message type. In this method the boolean value that has been changed is /// found then the message body is validated based on which boolean has been changed. /// </summary> /// <param name="inputText">Passes in the message body, to be validated</param> /// <returns>A boolean value which returns true if the message being input passes the validation based on the which boolean value is set to true /// from the method MessageHeaderInputValidation()</returns> public bool MessageBodyInputValidation(string inputText) { EmailAddressAttribute emailAddressCheck = new EmailAddressAttribute(); PhoneAttribute phoneNumberCheck = new PhoneAttribute(); // SMS Validation // This IF statement deals with the validation if the message has been identified as a SMS if (smsMessage.Equals(true)) { bool smsCheck = true; smsMessage = false; // while loop that extracts the phone number then uses the IsValid() from the PhoneAttribute class while (smsCheck) { if (inputText.Length > 20) { for (int i = 20; i > 7; i--) { // Creates a substring then checks that value with IsValid() sender = inputText.Trim().Substring(0, i); // If the value is a valid phone number, inputText minus the phone number is set to the string text if (phoneNumberCheck.IsValid(sender)) { text = inputText.Trim().Substring(i); smsCheck = false; break; } } } else if (inputText.Length > 7 && inputText.Length < 21) { for (int i = inputText.Length; i > 7; i--) { // Creates a substring then checks that value with IsValid() sender = inputText.Trim().Substring(0, i); // If the value is a valid phone number, inputText minus the phone number is set to the string text if (phoneNumberCheck.IsValid(sender)) { text = inputText.Trim().Substring(i); smsCheck = false; break; } } } else { MessageBox.Show("The phone number entered, is not a valid phone number."); return(false); } } // Checks the length of the SMS if (text.Length > 140) { MessageBox.Show("The SMS is too long. It can only be upto a maximum of 140 characters"); return(false); } SetPublicVariable(); return(true); } // EMAIL Validation // This IF statement deals with the validation if the message has been identified as a Email if (emailMessage.Equals(true)) { emailMessage = false; string[] splitProText = inputText.Trim().Split(' '); string[] nameArray = { }; string[] subjectAndTextArray = { }; string subjectAndText = string.Empty; bool emailAddressFound = false; for (int i = 0; i < splitProText.Length; i++) { if (splitProText[i].Contains("@")) { // Checks if the email is a valid email address if (emailAddressCheck.IsValid(splitProText[i])) { emailAddressFound = true; sender = splitProText[i]; splitProText[i] = ""; nameArray = splitProText.Take(i).ToArray(); subjectAndTextArray = splitProText.Skip(i).ToArray(); break; } } } if (emailAddressFound.Equals(false)) { MessageBox.Show("You have entered an incorrect email address."); return(false); } // Concatenate all the elements into a StringBuilder. StringBuilder nameBuilder = new StringBuilder(); foreach (string value in nameArray) { nameBuilder.Append(value); nameBuilder.Append(' '); } name = nameBuilder.ToString().Trim(); // Concatenate all the elements into a StringBuilder. StringBuilder subjectAndTextBuilder = new StringBuilder(); foreach (string value in subjectAndTextArray) { subjectAndTextBuilder.Append(value); subjectAndTextBuilder.Append(' '); } subjectAndText = subjectAndTextBuilder.ToString().Trim(); if (subjectAndText.ToUpper().StartsWith("SIR")) { // Creates substrings from newInputText subject = subjectAndText.Trim().Substring(0, 12); text = subjectAndText.Trim().Substring(12); } else { // Creates substrings from newInputText subject = subjectAndText.Trim().Substring(0, 20); text = subjectAndText.Trim().Substring(20); } // Checks the email doesn't exceed the maximum length if (text.Length > 1048) { MessageBox.Show("This email is longer than 1028 max characters"); return(false); } SetPublicVariable(); return(true); } // TWEET Validation // This IF statement deals with the validation if the message has been identified as a Tweet if (tweetMessage.Equals(true)) { tweetMessage = false; string[] splitProText = inputText.Trim().Split(' '); if (splitProText[0].StartsWith("@") && splitProText[0].Length < 16) { sender = splitProText[0]; splitProText[0] = string.Empty; } else { MessageBox.Show("You have entered an incorrect Twitter ID.\nPlease check and try again."); return(false); } // Concatenate all the elements into a StringBuilder. StringBuilder builder = new StringBuilder(); foreach (string value in splitProText) { builder.Append(value); builder.Append(' '); } text = builder.ToString().Trim(); // Checks that the tweet text length is less than 140 characters if (text.Length > 140) { MessageBox.Show("The tweet text is more than 140 characters in length."); return(false); } SetPublicVariable(); return(true); } return(false); }
/// <summary> /// Init /// </summary> public ValidatePhoneAttribute() : base(DataType.PhoneNumber) { ErrorMessage = new PhoneAttribute().ErrorMessage; }
public static void Validate_successful_for_empty_value() { var attribute = new PhoneAttribute(); Assert.True(attribute.IsValid(string.Empty)); }
public static void Validate_successful_for_null_value() { var attribute = new PhoneAttribute(); Assert.True(attribute.IsValid(null)); }