Ensure the input the user gave is of a valid format
5500
def valid_input(val):
        
        # looks for 3 nums followed by a dot 3 times and then ending with
        # 3 nums, can be proceeded by any number of spaces
        ip_value = re.compile(r'(\d{1,3}\.){3}\d{1,3}$')
        # looks for only numbers and commas (because priorities can have commas
        # between them), can be proceeded by any number of spaces
        all_num = re.compile(r'(\d,?\ *)+$')
        sections_comments = re.compile(r"""
        \ *\#.*             # comments (any number of whitespace, then #
                            # followed by anything)

        | \[[\w-]+\]$       # section headers (any combination of chars, nums,
                            # underscores, and dashes between brackets)
        """, re.VERBOSE)
        # can't can be a comment on option side and value side can't have
        # [, ], {, or } otherwise it is turned over to literal_eval for
        # checkout
        options_values = re.compile(r'[^# ]+\ *=[^[\]{}]*$')
        line_num = 0
        warning_str = ''
        error_str = ''
        trimmed_val = []
        for entry in val.split('\n'):
            line_num += 1
            # get rid of any extraneous commas at the end of a dict and remove
            # extra whitespace from input
            trimmed_val.append(re.sub(r',\ *}', '}', entry).strip())
            # empty line
            if entry.strip() == '':
                continue
            # look at regular (non dictionary or list) option-value pairs
            if options_values.match(entry):
                value = entry.split('=', 1)[1]
                # deal with potentially more equals signs
                for val in value.split('='):
                    val = val.strip()
                    # empty val means malformed equals signs
                    if val == '':
                        error_str += '-You have a misplaced equals sign on' \
                            ' line ' + str(line_num) + '\n'
                    # starts with a num; look for bad ip input or warn user
                    # about having extraneous characters in number input
                    if re.match('\ *\d', val):
                        # bad ip syntax
                        if val.find('.') >= 0 and not ip_value.match(val):
                            error_str += '-You have an incorrectly' \
                                ' formatted ip address (bad syntax) at' \
                                ' line ' + str(line_num) + '\n'
                        # possibly malformed numbers
                        elif val.find('.') < 0 and not all_num.match(val):
                            warning_str += '-Line starting with a number has' \
                                ' characters mixed in at line ' + \
                                str(line_num) + '\n'
                        # bad ip values
                        elif val.find('.') >= 0:
                            for num in val.strip().split('.'):
                                num = int(num)
                                if num > 255 or num < 0:
                                    error_str += '-You have an incorrectly' \
                                        ' formatted ip address (values' \
                                        ' exceeding 255 or below 0) at' \
                                        ' line ' + str(line_num) + '\n'
                    # ensure no lines end with a comma (most likely extraneous
                    # commas from groups or priorities)
                    if re.search(',$', val):
                        error_str += '-You have an incorrect comma at the' \
                            ' end of line ' + str(line_num) + '\n'
            # see if input is a header or comment, otherwise try to
            # literal_eval it to ensure correct structure
            elif not sections_comments.match(entry):
                lit_val = ''
                try:
                    opt_val = entry.split('=', 1)
                    if opt_val[0].strip() == '':
                        error_str += '-You have nothing preceeding an' \
                            ' equals sign at line ' + str(line_num) + '\n'
                    else:
                        lit_val = opt_val[1].strip()
                except IndexError:
                    lit_val = ''
                    error_str += '-You have an incorrectly formatted' \
                        ' section header at line ' + str(line_num) + '\n'
                if lit_val:
                    try:
                        ast.literal_eval(lit_val)
                    except SyntaxError:
                        error_str += '-You have an incorrectly formatted' \
                            ' list/dictionary at line ' + str(line_num) + \
                            '\n'

        if error_str:
            npyscreen.notify_confirm('You have the following error(s) and'
                                     " can't proceed until they are fixed:" +
                                     '\n' + '-'*50 + '\n' + error_str,
                                     title='Error in input')
            return (False, '')
        elif warning_str:
            res = npyscreen.notify_yes_no('You have may have some error(s)'
                                          ' that you want to check before'
                                          ' proceeding:' + '\n' + '-'*50 +
                                          '\n' + warning_str + '\n' + '-'*50 +
                                          '\n' + 'Do you want to continue?',
                                          title='Double check')
            return (res, '\n'.join(trimmed_val))
        return (True, '\n'.join(trimmed_val))
921736
def _validated(self, data):
        """"""
        try:
            return self.convert(data)
        except (TypeError, ValueError) as ex:
            raise NotValid(*ex.args)
89190
function validateFormatParameters(that, format, obj) {
        if ('string' !== typeof format &&
            !J.isArray(format) && !format.length) {

            that.throwErr('TypeError', 'addFormat', 'format must be ' +
                            'a non-empty string or array');
        }
        if ('object' !== typeof obj) {
            that.throwErr('TypeError', 'addFormat', 'obj must be object');
        }
        if (!obj.save && !obj.saveSync) {
            that.throwErr('Error', 'addFormat', 'format must ' +
                          'at least one save function: sync or async');
        }
        if (!obj.load && !obj.loadSync) {
            that.throwErr('Error', 'addFormat', 'format must ' +
                          'at least one load function: sync or async');
        }
        if (obj.save || obj.load) {
            if ('function' !== typeof obj.save) {
                that.throwErr('TypeError', 'addFormat',
                              'save function is not a function');
            }
            if ('function' !== typeof obj.load) {
                that.throwErr('TypeError', 'addFormat',
                              'load function is not a function');
            }
        }
        if (obj.saveSync || obj.loadSync) {
            if ('function' !== typeof obj.saveSync) {
                that.throwErr('TypeError', 'addFormat',
                              'saveSync function is not a function');
            }
            if ('function' !== typeof obj.loadSync) {
                that.throwErr('TypeError', 'addFormat',
                              'loadSync function is not a function');
            }
        }
    }
693423
def is_valid(self, qstr=None):
        """"""
        if qstr is None:
            qstr = self.currentText()
        return osp.isdir(to_text_string(qstr))
145116
def get_input(input_func, input_str):
    
    val = input_func("Please enter your {0}: ".format(input_str))
    while not val or not len(val.strip()):
        val = input_func("You didn't enter a valid {0}, please try again: ".format(input_str))
    return val
309306
def validate(self, value, redis):
        '''
        
        '''
        # cleanup
        if type(value) == str:
            value = value.strip()

        value = self.value_or_default(value)

        # validation
        self.validate_required(value)

        if self.regex and not re.match(self.regex, value, flags=re.ASCII):
            raise InvalidFieldError(self.name)

        if self.forbidden and value in self.forbidden:
            raise ReservedFieldError(self.name)

        if self.allowed and value not in self.allowed:
            raise InvalidFieldError(self.name)

        if self.index:
            key = self.key()

            old = debyte_string(redis.hget(key, value))
            old_value = getattr(self.obj, self.name)

            if old is not None and old != self.obj.id:
                raise NotUniqueFieldError(self.name)
            elif old_value != value:
                self.obj._old[self.name] = old_value

        return value
599004
def _validate_file_format(self, file_format):
        """"""

        if file_format not in self.valid_file_formats:
            raise InvalidFileFormatError(
                "{} is not a valid file format".format(file_format)
            )

        return file_format
625743
def acceptable(value, capitalize=False):
    """"""
    name = regexes['punctuation'].sub("", regexes['joins'].sub("_", value))
    # Clean up irregularities in underscores.
    name = regexes['repeated_underscore'].sub("_", name.strip('_'))
    if capitalize:
        # We don't use python's built in capitalize method here because it
        # turns all upper chars into lower chars if not at the start of
        # the string and we only want to change the first character.
        name_parts = []
        for word in name.split('_'):
            name_parts.append(word[0].upper())
            if len(word) > 1:
                name_parts.append(word[1:])
        name = ''.join(name_parts)
    return name
392146
def validate_pluginid(value):
    ''''''
    valid = string.ascii_letters + string.digits + '.'
    return all(c in valid for c in value)
1005776
private boolean checkAnswer(String input) {
        StringTokenizer tok = new StringTokenizer(validAnswers, ANSWER_SEPARATOR);

        while (tok.hasMoreTokens()) {
            if (tok.nextElement().toString().trim().equalsIgnoreCase(input.trim())) {
                return true;
            }
        }

        log.info("User input is not valid - must be one of " + validAnswers);

        return false;
    }
1083272
def _check_valid(key, val, valid):
    """"""
    if val not in valid:
        raise ValueError('%s must be one of %s, not "%s"'
                         % (key, valid, val))
682024
def Validate(self, value, **_):
    """"""
    if isinstance(value, rdfvalue.RDFString):
      # TODO(hanuszczak): Use `str` here.
      return Text(value)

    if isinstance(value, Text):
      return value

    if isinstance(value, bytes):
      return value.decode("utf-8")

    raise type_info.TypeValueError("Not a valid unicode string: %r" % value)
1179215
def validate_options(self, k, v):
        """"""

        super().validate_options(k, v)
        if k == 'charset_size':
            if v not in (1, 2, 4):
                raise ValueError("{}: '{}' is an unsupported charset size".format(self.__class__.__name__, v))
        elif k == 'wide_charset_size':
            if v not in (2, 4):
                raise ValueError("{}: '{}' is an unsupported wide charset size".format(self.__class__.__name__, v))
        elif k in ('exec_charset', 'wide_exec_charset'):
            # See if parsing fails.
            self.get_encoding_name(v)
        elif k == 'string_types':
            if RE_VALID_STRING_TYPES.match(v) is None:
                raise ValueError("{}: '{}' does not define valid string types".format(self.__class__.__name__, v))
1138764
def ensure_unicode(str_or_unicode):
    
    if isinstance(str_or_unicode, str):
        return str_or_unicode.decode('utf-8')
    elif isinstance(str_or_unicode, unicode):
        return str_or_unicode
    else:
        raise ValueError("Input '{0}' should be a string or unicode, "
                         "but its of type {1}".format(str_or_unicode,
                                                      type(str_or_unicode)))
818329
function formatInput(val, countryCode, addSuffix, allowExtension, isAllowedKey) {
    try {
        var clean = val.replace(/\D/g, ""),
            // NOTE: we use AsYouTypeFormatter because the default format function can't handle incomplete numbers e.g. "+17024" formats to "+1 7024" as opposed to "+1 702-4"
            formatter = new i18n.phonenumbers.AsYouTypeFormatter(countryCode),
            // if clean is empty, we still need this to be a string otherwise we get errors later
            result = "",
            next,
            extSuffix = " ext. ";

        if (val.substr(0, 1) == "+") {
            clean = "+" + clean;
        }

        for (var i = 0; i < clean.length; i++) {
            // TODO: improve this so don't just pump in every digit every time - we should just cache this formatter object, and just call inputDigit once each time the user enters a new digit
            next = formatter.inputDigit(clean.charAt(i));
            // if adding this char didn't change the length, or made it smaller (and there's no longer any spaces): that means that formatting failed which means the number was no longer a potentially valid number, so if we're allowing extensions: assume the rest is the ext
            if (allowExtension && result && next.length <= result.length && next.indexOf(" ") == -1) {
                // set flag for extension
                next = -1;
                break;
            }
            result = next;
        }

        // for some reason libphonenumber formats "+44" to "+44 ", but doesn't do the same with "+1"
        if (result.charAt(result.length - 1) == " ") {
            result = result.substr(0, result.length - 1);
        }
        // check if there's a suffix to add (unless there's an ext)
        if (addSuffix && !val.split(extSuffix)[1]) {
            // hack to get formatting suffix
            var test = formatter.inputDigit('5');
            // again the "+44 " problem... (also affects "+45" apparently)
            if (test.charAt(test.length - 1) == " ") {
                test = test.substr(0, test.length - 1);
            }
            // if adding a '5' introduces a formatting char - check if the penultimate char is not-a-number
            var penultimate = test.substr(test.length - 2, 1);
            // Note: never use isNaN without parseFloat
            if (isNaN(parseFloat(penultimate))) {
                // return the new value (minus that last '5' we just added)
                return test.substr(0, test.length - 1);
            } else if (allowExtension && result && test.length <= result.length && test.indexOf(" ") == -1 && !isAllowedKey) {
                // else if the next digit would break the formating, and we're allowing extensions, AND this is not an allowed key: add the suffix
                // NOTE: we must check this is not an allowed key because if it was that means it was the last digit in a valid number and we dont want to add the "ext" suffix in that case. This whole condition is just here to catch the case that: after typing a valid number, they try to type "ext" - this will not automatically add it for them.
                return result + extSuffix;
            }
        }

        // if the clean number contains an extension we need to add it
        if (next == -1) {
            result += extSuffix + clean.substring(i, clean.length);
        }

        return result;
    } catch (e) {
        return val;
    }
}
1049679
def handle_input(self, input_str, place=True, check=False):
        ''''''
        user = self.get_player()
        pos = self.validate_input(input_str)
        if pos[0] == 'u':
            self.undo(pos[1])
            return pos
        if place:
            result = self.set_pos(pos, check)
            return result
        else:
            return pos
801596
def prep_value(self, value):
        
        if value in MULTI_EMAIL_FIELD_EMPTY_VALUES:
            return ""
        elif isinstance(value, six.string_types):
            return value
        elif isinstance(value, list):
            return "\n".join(value)
        raise ValidationError('Invalid format.')