检查用户输入的字符串是否只包含大写 and/or 小写字母
Check if user input string contains only uppercase and/or lowercase letters
我正在创建一个 Chrome 扩展程序,将核苷酸序列转换成相应的氨基酸,我 运行 在验证用户输入方面遇到了一些问题。
我最终想检查以确保用户只输入了大写或小写字符(没有数字、特殊字符、空格等)。如果发现任何不可接受的字符,它会警告用户输入无效。否则,程序将照常进行,不会抛出 error/alert。
下面是我目前拥有的 JavaScript 代码。我已经尝试了一些基于 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 的变体以供参考。
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);
}
我相信这会有所帮助。
//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) );
使用此模式检查:/^[a-zA-Z]+$/i.test(yourStr);
这最终对我有用:
// 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;
}
我正在创建一个 Chrome 扩展程序,将核苷酸序列转换成相应的氨基酸,我 运行 在验证用户输入方面遇到了一些问题。
我最终想检查以确保用户只输入了大写或小写字符(没有数字、特殊字符、空格等)。如果发现任何不可接受的字符,它会警告用户输入无效。否则,程序将照常进行,不会抛出 error/alert。
下面是我目前拥有的 JavaScript 代码。我已经尝试了一些基于 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 的变体以供参考。
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);
}
我相信这会有所帮助。
//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) );
使用此模式检查:/^[a-zA-Z]+$/i.test(yourStr);
这最终对我有用:
// 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;
}