如何编写用逗号分隔输入以及输入是否在换行符上的javascript错误



我正试图在javascript上写一个错误。首先,如果输入文本没有用逗号分隔,然后如果输入文本的每个实例都不在新行上,则会出现另一个错误。即使输入正确,我当前的错误也会显示出来。

以下是功能:

function verify(){
if(!document.getElementById('input-text').value.trim().length){
alert("Cannot be empty. Enter the module names and marks separated by comma [put each module in a new line]");
}else if(document.getElementById('input-text').value != input_text.match(/[^rn]+/g)){
alert("Module names and marks must be seperated by a comma.");
}
}

定义输入文本的

Student Grade Checker App
</div>
<div>
<textarea class="display-input" id="input-text" rows="5" cols="35" required minlength="2" placeholder="Enter the module names and marks separated by comma [put each module in a new line]" value="">Enter the module names and marks separated by comma [put each module in a new line]</textarea>
</div>
<div>
<textarea class="display-output" id="output-text" rows="5" cols="35" readonly=1 placeholder="Results here..." value="">
</textarea>
</div>
<div>
<button class="sgcbutton-active" onclick="verify();getTotal();">Total Marks</button>
</div>

接受的输入文本

编程,70
数据,60
计算,40

我认为目标是检测非空的、有逗号的文本,并且每个逗号后面都有一个换行符(最后一位是猜测,但对于输入列表的文本区域来说,这听起来很明智。

function verify() {
let input = document.getElementById('input-text').value;
if (!input.trim()) {
alert("Cannot be empty. Enter the module names and marks separated by comma [put each module in a new line]");
return false;
}
let comps = input.split(',');
// is it okay to have no commas? if not
if (comps.length === 1) {
alert("you need at least one comma, right?");
return false;
}
// if every comma must be followed by a newline, then every element
// in comps after the first one must begin with n
if (!comps.slice(1).every(s => s.startsWith('n'))) {
alert("every comma must be followed with a newline");
return false;
}
return true;
}

最新更新