Pattern validator Validates that the value has to match the pattern specified. Can be a regular expression or the name of one of the built in patterns
189459
function(value, attr, pattern, model) {
        if (!hasValue(value) || !value.toString().match(defaultPatterns[pattern] || pattern)) {
          return this.format(getMessageKey(this.msgKey, defaultMessages[pattern]) || defaultMessages.inlinePattern, this.formatLabel(attr, model), pattern);
        }
      }
1211331
def _validate(self):
        
        errors = {}

        for name, validator in self._validators.items():
            value = getattr(self, name)

            try:
                validator(self, value)
            except ValidationError as e:
                errors[name] = str(e)

        self._validate_errors = errors
233141
function verify(context, node, pattern, flags) {
    try {
        let found = false

        new RegExpValidator({
            onCapturingGroupEnter(_start, name) {
                if (name) {
                    found = true
                }
            },
            onBackreference(_start, _end, ref) {
                if (typeof ref === "string") {
                    found = true
                }
            },
        }).validatePattern(pattern, 0, pattern.length, flags.includes("u"))

        if (found) {
            context.report({ node, messageId: "forbidden" })
        }
    } catch (error) {
        //istanbul ignore else
        if (error.message.startsWith("Invalid regular expression:")) {
            return
        }
        //istanbul ignore next
        throw error
    }
}
880827
def validate_regex(ctx, param, value):
    
    if not value:
        return None

    try:
        re.compile(value)
    except re.error:
        raise click.BadParameter('Invalid regex "{0}" provided'.format(value))

    return value
946092
public static Constraint pattern(final Object regex) {
		return new Constraint("pattern", patternPayload(regex)) {
			public boolean isValid(Object actualValue) {
				if (actualValue != null) {
					if (regex != null && regex instanceof String) {
						if (!(actualValue instanceof String) || !((String) actualValue).matches((String) regex)) {
							return false;
						}
					}
				}
				return true;
			}
		};
	}
494836
def validate(self, input_string):
        
        validation_result = False
        try:
            validation_result = bool(match(pattern=self.pattern, string=input_string))
        except TypeError as e:
            self.log.error(
                'Exception while validating Regex, pattern={}, input_string={} - exception: {}'.format(self.pattern,
                                                                                                       input_string,
                                                                                                       e))
        return validation_result
128739
def run_validator(pattern):
    

    start = ''
    if isinstance(pattern, six.string_types):
        start = pattern[:2]
        pattern = InputStream(pattern)

    if not start:
        start = pattern.readline()[:2]
        pattern.seek(0)

    parseErrListener = STIXPatternErrorListener()

    lexer = STIXPatternLexer(pattern)
    # it always adds a console listener by default... remove it.
    lexer.removeErrorListeners()

    stream = CommonTokenStream(lexer)

    parser = STIXPatternParser(stream)
    parser.buildParseTrees = False
    # it always adds a console listener by default... remove it.
    parser.removeErrorListeners()
    parser.addErrorListener(parseErrListener)

    # To improve error messages, replace "<INVALID>" in the literal
    # names with symbolic names.  This is a hack, but seemed like
    # the simplest workaround.
    for i, lit_name in enumerate(parser.literalNames):
        if lit_name == u"<INVALID>":
            parser.literalNames[i] = parser.symbolicNames[i]

    parser.pattern()

    # replace with easier-to-understand error message
    if not (start[0] == '[' or start == '(['):
        parseErrListener.err_strings[0] = "FAIL: Error found at line 1:0. " \
                                          "input is missing square brackets"

    return parseErrListener.err_strings
305364
function validateExpression( node ) {
		var args,
			len,
			re,
			i;

		if ( node.callee.name === 'RegExp' ) {
			len = node.arguments.length;
			args = new Array( node.arguments.length );
			for ( i = 0; i < len; i++ ) {
				// NOTE: we only support literals ATM. Otherwise, we may need to walk and implement an entire tree.
				if ( node.arguments[ i ].type !== 'Literal' ) {
					return;
				}
				args[ i ] = node.arguments[ i ].value;
			}
			re = RegExp.apply( null, args );
			if ( !safe( re ) ) {
				context.report( node, 'Unsafe regular expression' );
			}
		}
	}
1096169
def _determine_validator_type(self, data_type, value, has_default):
        """"""
        data_type, nullable = unwrap_nullable(data_type)

        validator = None

        if is_list_type(data_type):
            item_validator = self._determine_validator_type(
                data_type.data_type, value, False)
            item_validator = item_validator if item_validator else 'nil'

            validator = '{}:{}'.format(
                fmt_validator(data_type),
                fmt_func_args([
                    ('minItems', '@({})'.format(data_type.min_items)
                     if data_type.min_items else 'nil'),
                    ('maxItems', '@({})'.format(data_type.max_items)
                     if data_type.max_items else 'nil'),
                    ('itemValidator', item_validator),
                ]))
        elif is_map_type(data_type):
            item_validator = self._determine_validator_type(
                data_type.value_data_type, value, False)
            item_validator = item_validator if item_validator else 'nil'

            validator = '{}:{}'.format(
                fmt_validator(data_type),
                fmt_func_args([
                    ('itemValidator', item_validator),
                ]))
        elif is_numeric_type(data_type):
            if data_type.min_value or data_type.max_value:
                validator = '{}:{}'.format(
                    fmt_validator(data_type),
                    fmt_func_args([
                        ('minValue', '@({})'.format(data_type.min_value)
                         if data_type.min_value else 'nil'),
                        ('maxValue', '@({})'.format(data_type.max_value)
                         if data_type.max_value else 'nil'),
                    ]))
        elif is_string_type(data_type):
            if data_type.pattern or data_type.min_length or data_type.max_length:
                pattern = data_type.pattern.encode('unicode_escape').replace(
                    "\"", "\\\"") if data_type.pattern else None
                validator = '{}:{}'.format(
                    fmt_validator(data_type),
                    fmt_func_args([
                        ('minLength', '@({})'.format(data_type.min_length)
                         if data_type.min_length else 'nil'),
                        ('maxLength', '@({})'.format(data_type.max_length)
                         if data_type.max_length else 'nil'),
                        ('pattern', '@"{}"'.format(pattern)
                         if pattern else 'nil'),
                    ]))

        if nullable:
            if validator:
                validator = fmt_func_call(
                    caller='DBStoneValidators', callee=validator)
                validator = fmt_func_call(
                    caller='DBStoneValidators',
                    callee='nullableValidator',
                    args=validator)
        else:
            if validator:
                validator = fmt_func_call(
                    caller='DBStoneValidators', callee=validator)
            else:
                validator = 'nil'
            if not has_default:
                validator = fmt_func_call(
                    caller='DBStoneValidators',
                    callee='nonnullValidator',
                    args=validator)
            else:
                validator = None
        return validator
515698
def regexpr_validator(value):
    
    try:
        re.compile(value)
    except re.error:
        raise ValidationError(
            _('"%(value)s" is not a valid regular expression'),
            params={'value': value}
        )
104957
public static boolean matches(Pattern patternMatcher, Object... elements)
    {
        if (patternMatcher == null) {
            return true;
        }

        for (Object element : elements) {
            if (matches(patternMatcher, element)) {
                return true;
            }
        }

        return false;
    }
1229864
public static boolean safeRegexMatch(String pattern, String value) {
        if (StringUtils.isNotBlank(pattern)) {
            if (value == null) {
                return false;
            } else {
                try {
                    return Pattern.matches(pattern, value);
                } catch (PatternSyntaxException ex) {
                    return false;
                }
            }
        } else {
            return false;
        }
    }
66296
private static boolean match(String regExp, String userInput) {
        Pattern pattern = Pattern.compile(regExp);
        Matcher matcher = pattern.matcher(userInput);
        if (matcher.find())
            return true;
        else
            return false;
    }
529731
def match(pattern):
    
    regex = re.compile(pattern)

    def validate(value):
        if not regex.match(value):
            return e("{} does not match the pattern {}", value, pattern)
    return validate
325624
public static String stringMatcherByPattern(String input, String patternStr) {

        String output = PcConstants.SYSTEM_FAIL_MATCH_REGEX;

        // 20140105: fix the NPE issue
        if (patternStr == null) {
            logger.error("patternStr is NULL! (Expected when the aggregation rule is not defined at "
                    + PcDateUtils.getNowDateTimeStrStandard());
            return output;
        }

        if (input == null) {
            logger.error("input (Expected when the response is null and now try to match on response) is NULL in stringMatcherByPattern() at "
                    + PcDateUtils.getNowDateTimeStrStandard());
            return output;
        } else {
            input = input.replace("\n", "").replace("\r", "");
        }

        logger.debug("input: " + input);
        logger.debug("patternStr: " + patternStr);

        Pattern patternMetric = Pattern.compile(patternStr, Pattern.MULTILINE);

        final Matcher matcher = patternMetric.matcher(input);
        if (matcher.matches()) {
            output = matcher.group(1);
        }
        return output;
    }
1144496
public boolean match(String str, String regex) {
		if (str == null || regex == null)
			return false;
		if (regex.trim().isEmpty())
			return true;
		return Pattern.compile(regex.trim()).matcher(str).find();
	}
1308863
def validate(self, value):
        
        errors = []
        self._used_validator = []
        for val in self._validators:
            try:
                val.validate(value)
                self._used_validator.append(val)
            except ValidatorException as e:
                errors.append(e)
            except Exception as e:
                errors.append(ValidatorException("Unknown Error", e))
        if len(errors) > 0:
            raise ValidatorException.from_list(errors)
        return value