开发者

Javascript Textbox "Scrubber"

I have not found a good solution: I have a text box in which users need to be able to type specific info into. For example the command might be "9030 OUT FU [1234 TEST]". I need to "scrub" this text box to ensure that the data was typed in exactly this format (caps not necessary). However there are approximately 50 of these different types of commands.

I am fairly new to javascript, but with good direction can understand it. Is this possible with javascript? Once the data is entered into the text box, it will run a function to return some information, and the text box will be clear for the next command. No 2 commands can be e开发者_StackOverflowntered at the same time. I just need to check the format is 100% accurate for each command. Any help is appreciated, thank you.


<script type="text/javascript">   
function scrub(text) {
    var commands = new Array{"someCommand","anotherCommand",...};
    for (var i = 0; i <= commands.length; i++) {
        if (text.value.toLowerCase().equals(commands[i])) {
            //command is valid; do something here
        } else {
           alert("Invalid command");
        }
    }
    text.value = ""; //clears the text box
}
</script>

For your textarea do this:

<textarea onblur="scrub(this);" ...></textarea>


Is there a set of keywords? And can be they be combined only in a certain fashion?

Looks like couple of regex patterns will be able to do the trick.

e.g: to match "9030 OUT FU [1234 TEST]" regex would be: /\d{4} OUT FU \[\d{4}\]/.

OUT FU and can be substituted with \w{3} and \w{2} respectively (unless you do not want any word to be allowed).


Use regular expressions.

html:

<input type="text" id="code" />
<input type="button" value="test" onclick="alert(checkCode())" />

javascript:

function checkCode(){
var code = document.getElementById('code').value;
return code.match(/\d+ \w+ \w+ \[\d+ \w+\]/)!=null ? true : false;
}

http://gskinner.com/RegExr/ is very helpful with regular expressions.

When you say "exactly this format", you have to understand that we have no clue what you mean. There are an infinite number of patterns that could be used to describe your example. The regular expression above will match if the code has a string of numbers, then a word, then another word, then an opening bracket, then a string of numbers, then a word, then a closing bracket.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜