简体   繁体   English

使用正则表达式检查管理员和用户的输入

[英]Checking input for admin and user using Regular Expression

I'm trying to create a function that will check the users input if it has the input of admin.我正在尝试创建一个函数,如果它有 admin 的输入,它将检查用户的输入。 It keeps on displaying correct even if its incorrect, but when I hard code the value of user input and admin it checks whether the output is correct or incorrect.即使不正确,它也会继续显示正确​​,但是当我对用户输入和管理员的值进行硬编码时,它会检查输出是正确还是不正确。 I want the users to input the value and check whether it is correct or wrong.我希望用户输入值并检查它是正确还是错误。

 var str = document.getElementById('user'); var str2 = document.getElementById('admin'); var reg = new RegExp(str2.value, "i"); var result = str.value.match(reg); function sample() { if (result) { document.getElementById('checker').innerHTML = "correct"; } else { document.getElementById('checker').innerHTML = "wrong"; } }
 <textarea id="admin" placeholder="admin" rows="5"></textarea> <textarea id="user" placeholder="user" rows="5"></textarea> <textarea id="checker"></textarea> <br> <button style="height: 50px; width: 100px;" onclick="sample()">Check</button>

The str2.value and str.value hold no value inside your sample() function as they are not defined in the function scope. str2.valuestr.value在您的sample()函数中没有值,因为它们没有在函数作用域中定义。 The code lines where these values are read from the input text boxes should be placed inside the sample() function body.从输入文本框中读取这些值的代码行应放置在sample()函数体内。

Another issue is that when you check whether a stirng contains another string with a regex, you should account for special chars in the str2.value .另一个问题是,当您检查一个带有正则表达式的字符串是否包含另一个字符串时,您应该考虑str2.value特殊字符。 Without properly escaping it, ( or ? , or even . would yield unwelcome behavior. You can use a simple non-regex solution from Contains case insensitive post here since you are using fixed string values here.如果没有正确转义它, (? ,甚至.会产生不受欢迎的行为。您可以使用来自包含不区分大小写的帖子here的简单非正则表达式解决方案,因为您在这里使用固定字符串值。

 function sample() { var str = document.getElementById('user'); var str2 = document.getElementById('admin'); if (str.value.toUpperCase().indexOf(str2.value.toUpperCase()) === -1) { document.getElementById('checker').innerHTML = "correct"; } else { document.getElementById('checker').innerHTML = "wrong"; } }
 <textarea id="admin" placeholder="admin" rows="5"></textarea> <textarea id="user" placeholder="user" rows="5"></textarea> <textarea id="checker"></textarea> <br> <button style="height: 50px; width: 100px;" onclick="sample()">Check</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM