public async Task ValidateAsync(UserManager <TUser> manager, TUser user, ICollection <IdentityError> errors)
        {
            var phoneNumber = await manager.GetPhoneNumberAsync(user);

            if (!_options.Value.User.RequirePhoneNumber && string.IsNullOrWhiteSpace(phoneNumber))
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(phoneNumber) || ContainsDeniedPhoneNumberCharacters(phoneNumber) ||
                !PhoneAttribute.IsValid(phoneNumber))
            {
                errors.Add(_describer.InvalidPhoneNumber(phoneNumber));
                return;
            }

            var exists = await manager.FindByNameAsync(phoneNumber);

            if (exists == null)
            {
                return;
            }

            if (!_options.Value.User.RequireUniquePhoneNumber)
            {
                return;
            }

            if (!string.Equals(await manager.GetUserIdAsync(exists), await manager.GetUserIdAsync(user)))
            {
                errors.Add(_describer.DuplicatePhoneNumber(phoneNumber));
            }
        }
        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);
        }
Exemplo n.º 3
0
    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));
    }
Exemplo n.º 4
0
        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"));
        }
Exemplo n.º 5
0
        public PhoneNumber(string phone)
        {
            if (!_phoneValidator.IsValid(phone))
            {
                throw new ArgumentException(nameof(phone), "{phone} is not valid phone");
            }

            _value = phone;
        }
Exemplo n.º 6
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var phone = new PhoneAttribute();

            if (!phone.IsValid(value))
            {
                return(new ValidationResult(FormatErrorMessage(validationContext.DisplayName)));
            }
            return(null);
        }
Exemplo n.º 7
0
        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");
        }
Exemplo n.º 8
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var phones = value as string;

            if (phones == null)
            {
                return(null);
            }

            var phonesArray = phones.Split(';');

            return(phonesArray.Select(phone => _phoneAttribute.IsValid(phone)).Any(validationResult => !validationResult) ?
                   new ValidationResult("NotAPhoneNumber") : null);
        }
Exemplo n.º 9
0
        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);
        }
Exemplo n.º 10
0
        /// <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));
            }
        }
Exemplo n.º 11
0
        /// <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);
        }
Exemplo n.º 12
0
 public bool IsValid(string value) => _validator.IsValid(value);
Exemplo n.º 13
0
 public static IRuleBuilderOptions <T, string> PhoneNumber <T>(
     this IRuleBuilder <T, string> ruleBuilder) =>
 ruleBuilder
 .Must(str => PhoneAttribute.IsValid(str))
 .WithMessage("{0} must be a phone number.");
Exemplo n.º 14
0
 public override bool IsValid(object value)
 {
     return(_emailAttr.IsValid(value) || _phoneAttr.IsValid(value));
 }
Exemplo n.º 15
0
        /// <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);
        }
Exemplo n.º 16
0
        public static void Validate_successful_for_null_value()
        {
            var attribute = new PhoneAttribute();

            Assert.True(attribute.IsValid(null));
        }
Exemplo n.º 17
0
        public static void Validate_successful_for_empty_value()
        {
            var attribute = new PhoneAttribute();

            Assert.True(attribute.IsValid(string.Empty));
        }