简体   繁体   English

如何编写 javascript 错误以用逗号分隔输入并且输入不在换行符上

[英]How to write javascript error for separating input by a comma and if input is not on a newline

I am trying to write an error on javascript.我试图在 javascript 上写一个错误。 Firstly if the input text is not separated by a comma and then another error if each instance of the input text is not on a new line.首先,如果输入文本没有用逗号分隔,然后如果输入文本的每个实例不在新行上,则会出现另一个错误。 What i have currently the error is being displayed even if the input is correct.即使输入正确,我目前的错误也会显示出来。

Here is the function:这是 function:

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(/[^\r\n]+/g)){
        alert("Module names and marks must be seperated by a comma.");
    }
}

Where input-text is being defined定义输入文本的地方

   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>

Accepted input text接受的输入文本

Programming,70编程,70
Data,60数据,60
Computing,40计算,40

I think the aim is to detect non-empty text that is non-empty, has commas, and every comma followed by a newline (that last bit is a guess, but its a sensible sounding thing for a text area for inputting a list.我认为目的是检测非空文本,它是非空的,有逗号,并且每个逗号后跟一个换行符(最后一位是猜测,但对于用于输入列表的文本区域来说,这是一个合理的声音。

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;
}

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

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