简体   繁体   中英

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. 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. The code lines where these values are read from the input text boxes should be placed inside the sample() function body.

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 . 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.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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