简体   繁体   English

如何在 function 中使用此正则表达式验证输入?

[英]How can I validate inputs using this regex within a function?

So i have a regex which i hope is sufficient to match my date input data.所以我有一个正则表达式,我希望它足以匹配我的日期输入数据。

I want to validate the dates before the getSum() function is executed.我想在执行 getSum() function 之前验证日期。 And if it does not match, I want to alert the user with some text.如果不匹配,我想用一些文本提醒用户。

I was thinking I need an If Else statement somewhere in the getSum function, but I am not sure where to put it.我在想我需要在 getSum function 的某处使用 If Else 语句,但我不知道该放在哪里。 As you can see, the getSum function first loops over an array of inputs, then within a.forEach, it extracts the value from each input field.如您所见,getSum function 首先循环输入数组,然后在 a.forEach 中,从每个输入字段中提取值。

I thought that this might be the place to begin an if else statement, because this is the point where the two inputs have their values determined.我认为这可能是开始 if else 语句的地方,因为这是两个输入确定其值的点。 I just need a way to compare those two values against my regex, and if they match, run the rest of the code as normal.我只需要一种方法将这两个值与我的正则表达式进行比较,如果它们匹配,则正常运行代码的 rest。 And if they dont match, then an else statement with an alert.如果它们不匹配,则带有警报的 else 语句。

Im not sure how to write this out.我不确定如何写出来。

var sumButton = document.querySelector(".sumNumbers");
sumButton.addEventListener("click", getSum);

var dateRegEx = /(0\d{1}|1[0-2])\/([0-2]\d{1}|3[0-1])\/(19|20)\d{2}/;

function getSum() {

  let inputs = ['dateInput1', 'dateInput2'];
  let outputs = ['result1', 'result2'];

  inputs.forEach(function(input, index) {
    const inputValue = document.getElementById(input).value;
    var sum = 0;
    for (var i = 0; i < inputValue.length; i++) {
      const num = parseInt(inputValue.charAt(i));
      if (!isNaN(num)) {
        sum += num;
      }
    }
    const total = (sum - 1) % 9 + 1;
    document.getElementById(outputs[index]).textContent = "Your number is: " + total;
  });
}

<form action="">
        <div class="container">

            <div class="cell-1" id="centerElement">
                <div id="cell-1-nest-l"></div>
                <div id="cell-2-nest-l"></div>
                <div id="cell-3-nest-l"></div>
                <div id="cell-4-nest-l"><h3>your name</h3></div>
                <div id="cell-5-nest-l"></div>
                <div id="cell-6-nest-l"><input type="text" 
class="nameStyle1" id="nameInput1" ></div>

      </div>

            <div class="cell-2" id="centerElement" ><img 
src="file:///Users/Nineborn/Downloads/My%20Post%20(5).png" alt="" 
class="sumNumbers"></div>

            <div class="cell-3" id="centerElement" >
                    <div id="cell-1-nest"></div>
                    <div id="cell-2-nest"></div>
                    <div id="cell-3-nest"><h3>their name</h3></div>
                    <div id="cell-4-nest"></div>
                    <div id="cell-5-nest"><input type="text" 
class="nameStyle1" id="nameInput2"></div>
                    <div id="cell-6-nest"></div>


                    </div>

            <div class="cell-4" id="result1">
                <input type="date" class="dateStyle1 reset" 
id="dateInput1">
                    </div>

            <div class="cell-5"><input type="reset"></div>

            <div class="cell-6" id="result2"> 
                <input type="date" class="dateStyle2" id="dateInput2" 
placeholder="Their Bday">
                    </div>
            <div class="cell-7"></div>

            <div class="cell-8"></div>

            <div class="cell-9"></div>


    </div>


    </form>

Put if (inputValue.match(dateRegEx)) around the code that calculates the sum.if (inputValue.match(dateRegEx))放在计算总和的代码周围。

When you use <input type="date"> , the format of the returned value is YYYY-MM-DD , not how it shows in the input field, which is formatted in whatever way is appropriate for the locale.当您使用<input type="date">时,返回值的格式是YYYY-MM-DD ,而不是它在输入字段中的显示方式,它以适合区域设置的任何方式格式化。 So you need to adjust the regexp accordingly.所以你需要相应地调整正则表达式。

Also, you should have ^ and $ anchors in the regexp so that it matches the entire input.此外,您应该在正则表达式中有^$锚点,以便它匹配整个输入。 Otherwise it will look for the pattern anywhere in the input.否则它将在输入中的任何位置查找模式。

 var sumButton = document.querySelector(".sumNumbers"); sumButton.addEventListener("click", getSum); var dateRegEx = /^(19|20)\d{2}-(0\d{1}|1[0-2])-([0-2]\d{1}|3[0-1])$/; function getSum() { let inputs = ['dateInput1', 'dateInput2']; let outputs = ['result1', 'result2']; inputs.forEach(function(input, index) { const inputValue = document.getElementById(input).value; if (inputValue.match(dateRegEx)) { var sum = 0; for (var i = 0; i < inputValue.length; i++) { const num = parseInt(inputValue.charAt(i)); if (;isNaN(num)) { sum += num; } } const total = (sum - 1) % 9 + 1. document.getElementById(outputs[index]):textContent = "Your number is; " + total. } else { document.getElementById(outputs[index]);textContent = "You entered an invalid date " + inputValue; } }); }
 Enter dates: <input type="date" id="dateInput1"> <input type="date" id="dateInput2"> <br> <button type="button" class="sumNumbers">Calculate sums</button> <div id="result1"></div> <div id="result2"></div>

我怎样才能添加多个输入到这个<div>使用 javascript function?</div><div id="text_translate"><p> 对于上下文,这是我正在开发的基于 Django 的应用程序。 我在 HTML 文档中使用此脚本。 当按下按钮时,它会运行以下 function。 目的是创建一个元素,然后包含几个输入等等。 我遇到的问题是,当我使用以下 append 语句向 div 添加一个输入时,如果我尝试添加另一个输入类型(例如复选框),它会覆盖第一个输入(搜索)。 如何在脚本中进行 append 多个输入? 我总共需要 3 个不同的输入。 </p><p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"><div class="snippet-code"><pre class="snippet-code-js lang-js prettyprint-override"> var counter = 1; //limits amount of transactions function addElements() { if (counter &lt; 5) //only allows 4 additional transactions { let div = document.createElement('div'); div.id = 'row' + counter; document.body.appendChild(div); let input = document.createElement('input'); input.id='search'+counter; input.type = 'search'; input.placeholder = 'Search by product name' div.appendChild(input); let button = document.createElement('button'); button.id ='button'+counter; button.type = 'QRscan'; button.innerText = 'QR scan' div.appendChild(button); } counter++ if (counter &gt;= 6) { alert("You have reached the maximum transactions.") } } addElements();</pre></div></div><p></p></div> - How can I add multiple inputs to this <div> using javascript function?

暂无
暂无

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

相关问题 如何使用.every() 方法验证针对正则表达式的输入? - How can I validate inputs against Regex using .every() method? 如何验证多个分组输入? - How can I validate multiple grouped inputs? 如何使用正则表达式验证我的文件输入名称? - How can I validate my file input name using regex? 如何使用 jQuery 验证多选输入和文本区域? - How can I validate multi-select inputs and textareas using jQuery? 我怎样才能添加多个输入到这个<div>使用 javascript function?</div><div id="text_translate"><p> 对于上下文,这是我正在开发的基于 Django 的应用程序。 我在 HTML 文档中使用此脚本。 当按下按钮时,它会运行以下 function。 目的是创建一个元素,然后包含几个输入等等。 我遇到的问题是,当我使用以下 append 语句向 div 添加一个输入时,如果我尝试添加另一个输入类型(例如复选框),它会覆盖第一个输入(搜索)。 如何在脚本中进行 append 多个输入? 我总共需要 3 个不同的输入。 </p><p></p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"><div class="snippet-code"><pre class="snippet-code-js lang-js prettyprint-override"> var counter = 1; //limits amount of transactions function addElements() { if (counter &lt; 5) //only allows 4 additional transactions { let div = document.createElement('div'); div.id = 'row' + counter; document.body.appendChild(div); let input = document.createElement('input'); input.id='search'+counter; input.type = 'search'; input.placeholder = 'Search by product name' div.appendChild(input); let button = document.createElement('button'); button.id ='button'+counter; button.type = 'QRscan'; button.innerText = 'QR scan' div.appendChild(button); } counter++ if (counter &gt;= 6) { alert("You have reached the maximum transactions.") } } addElements();</pre></div></div><p></p></div> - How can I add multiple inputs to this <div> using javascript function? 我如何使用 customvalidator 来验证 2 个输入,客户端 - How can I use customvalidator to validate 2 inputs, clientside 如何使用此jQuery Pluggin验证不同类型的输入/字段? - How Can I validate different types of inputs/fields with this jQuery Pluggin? 如何使用RegEx验证此要求 - How do i validate this requirements using RegEx 如何使用正则表达式验证没有I的范围AK? - How can I validate the range A-K without I, using a regex? 使用正则表达式验证输入文本时如何禁止字符串中的方括号 - How can I disallow a square bracket in a string when using regex to validate input text
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM