[英]Check if user input string contains only uppercase and/or lowercase letters
I'm creating a Chrome extension that converts a sequence of nucleotides into their corresponding amino acids, and I'm running into some problems with validating user input.我正在创建一个 Chrome 扩展程序,它将核苷酸序列转换为其相应的氨基酸,但我在验证用户输入时遇到了一些问题。
I ultimately want to check to make sure the user has input only uppercase or lowercase characters (no numbers, special characters, spaces, etc.).我最终想检查以确保用户只输入了大写或小写字符(没有数字、特殊字符、空格等)。 If any unacceptable characters are found, it alerts the user of invalid input.
如果发现任何不可接受的字符,它会提醒用户输入无效。 Otherwise, the program proceeds as normal and no error/alert is thrown.
否则,程序将照常进行,不会引发错误/警报。
Below is the JavaScript code I have currently.下面是我目前拥有的 JavaScript 代码。 I have tried a few variations based off of this post but I can't seem to get anything to work for me.
我已经根据这篇文章尝试了一些变体,但我似乎无法找到任何对我有用的东西。 With the code I have right now, when I try to submit valid input ("ATG" for example), the alert pops up instead of the program proceeding as normal and correctly outputting "M" (see this link for reference).
使用我现在拥有的代码,当我尝试提交有效输入(例如“ATG”)时,会弹出警报,而不是程序正常进行并正确输出“M”(请参阅此链接以供参考)。
document.getElementById('button').onclick = function () {
console.log(document.querySelectorAll("textarea"))
var n_seq = document.querySelectorAll("textarea")[0].value.toUpperCase();
// validate user input below
if (!/^[a-zA-Z]+$/i.test(n_seq)); {
alert("invald input");
return;
}
document.getElementById("amino_acid_seq").value = translateInput(codonDict, n_seq);
}
I believe this will be of help.我相信这会有所帮助。
//this will make the entire string uppercase
// that way you do not need to tell user to make sure its upper case
var input = document.querySelectorAll("textarea").toUpperCase();
//this is regex that will tell if its all letters. the i makes it case insesitve
var reg = /^[a-z]+$/i;
//this should output true or false
console.log( reg.test(input) );
This ended up working for me:这最终对我有用:
// only letters are acceptable characters, spaces, special characters, and
// numbers will throw an error
if (!/^[A-Z]+$/i.test(n_seq)) {
alert("Invalid input!");
return;
}
使用此模式检查: /^[a-zA-Z]+$/i.test(yourStr);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.