如何确定输入的模式是“Int,VarChar,Date,Time ...”等 [英] how to determine entered pattern is for `Int,VarChar,Date,Time...` etc

查看:92
本文介绍了如何确定输入的模式是“Int,VarChar,Date,Time ...”等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉列表,其中包含 DataType

和一个文本框,这是输入正则表达式图案

如果我在文本框中输入 / test /

或从下拉列表中选择 Int

如果在文本框中输入错误的格式 / [0-9] /

然后它的正确的模式。这里是我的小提琴链接

http://jsfiddle.net/VGF9B/2/


这是我的脚本

I have one drop-down its contain DataType.
and one text-box this this is for enter Regex Pattern.
if I am enter /test/ in textbox.
or select from drop-down Int
then its wrong pattern if enter in text-box /[0-9]/
then its correct pattern.
here is my fiddle link
http://jsfiddle.net/VGF9B/2/
this is my script

var dropdownValue = 'selectValue';
$('select').change(function(){
    dropdownValue = $(this).val();
});
$('#pattern').focusout(function(){
    alert(dropdownValue);
    var pattern = new RegExp($('#pattern').val());
    alert(pattern);
});

怎么可能?

推荐答案

我能想到的是使用例子,即应该与正则表达式匹配的典型输入:

What I could think about is to use examples, i.e. typical inputs that should match the regex:

var examples = {
    "Date": [
        "2010-01-01", "10-01-01", "2010-1-1", "10-1-1", "01-01-2010", "01-01-10", "1-1-2010", "1-1-10",
        "2010/01/01", "10/01/01", "2010/1/1", "10/1/1", "01/01/2010", "01/01/10", "1/1/2010", "1/1/10"
    ],
    "Int": [
        "0", "0123456789"
    ],
    "VarChar": [
        "a", "abcdefghijklmnopqrstuvwxyz", "A", "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    ]
};

然后,如果输入正则表达式与特定于类型的示例匹配,则可以使其有效:

Then, if the input regex matches one of the type-specific example, you could valid it:

$("#pattern").blur(function() {
    var pattern = this.value;
    var regex = new RegExp(pattern);
    var type = $("select").val();
    var validPattern = false;
    if (type in examples) {
        for (var i = 0; i < examples[type].length, i++) {
            var example = examples[i];
            if (regex.test(example)) {
                validPattern = true;
                break;
            }
        }
    } else {
        alert("No examples found for type '" + type + "'");
    }
    if (validPattern) {
        alert("Valid pattern");
    } else {
        alert("Invalid pattern");
    }
});

主要问题是它不会涵盖复杂/特殊的正则表达式。例如,带有 / ^ 5 / Int 对于给定的示例无效,因为没有 Int 5 开头的示例。带有 / bca / VarChar 也无效。但是如果你设法为每种类型设置足够的例子,这可能适合你的需要:)

The main problem is that it won't cover complex/special regexes. For example, Int with /^5/ won't be valid with the given examples, since there's no Int example starting with 5. VarChar with /bca/ won't be valid neither. But if you manage to have enough examples for each type, this could suit your needs :)

你可以看到一个例子这里

这篇关于如何确定输入的模式是“Int,VarChar,Date,Time ...”等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆