简体   繁体   English

提交表单后防止JS中的错误输入

[英]Prevent Wrong Input in JS After Submitting A Form

I am creating a sample MabLibs type thing in HTML and JS.我正在用 HTML 和 JS 创建一个示例 MabLibs 类型的东西。 When the person inputs stuff in a field, it will use that to create their own MadLib.当这个人在一个字段中输入内容时,它将使用它来创建他们自己的 MadLib。

I've done a little research and not finding exactly what I am looking for.我做了一些研究,但没有找到我正在寻找的东西。 Say a person puts 12 in the Name field.假设一个人在姓名字段中输入 12。 How would code that so if this instance does happen, it won't go through and alert "That is not a valid input. PLease type again!"将如何编码,以便如果此实例确实发生,它不会通过并警告“这不是有效输入。请再次输入!” or something along those lines.或类似的规定。

The code I am using is below.我正在使用的代码如下。 I am very new to Javascript so I know the format and stuff might be wrong.我对 Javascript 很陌生,所以我知道格式和内容可能是错误的。

<html><head>
<title>
  Mad Libs Story
</title>

<script>
  function getVars() {
    person1 = String(document.getElementById("personOne").value);
    age = Number(document.getElementById("ageOne").value);
    firstAdjective = String(document.getElementById("adjective").value);


    document.getElementById("madLibCreation").innerHTML = "There once was a person named " + person1 + ". She was " + age + " and very " + firstAdjective = ".";

  }
</script>
</head>
<body>
<h3>
Welcome to Mad Libs! Please type in the prompted Information. Then press the submit button. Have fun!   
</h3>  

<p>
  Name of Person in Room: <input type="text" id="personOne">
  </p>
<p>
  Age: <input type="text" id="ageOne">
  </p>
<p>
  Adjective: <input type="text" id="adjective">
  </p>



<input type="submit" value="Get My MadLib Creation!" onclick="getVars();">

<p id="madLibCreation"></p>

</body></html>

For that, you have to check Name field value is number or not.为此,您必须检查 Name 字段值是否为数字。 We can check the value is number or not using isNaN function.我们可以使用 isNaN 函数检查值是否为数字。 This function returns true or false.此函数返回真或假。

isNaN(12)           // falsee
isNaN(-4.5)         // false
isNaN(15-3)         // false
isNaN(0)            // false
isNaN('123')        // false
isNaN('Nuwan')      // true
isNaN('2005/12/12') // true
isNaN()             // true

So, in your code getVars() function change like this因此,在您的代码中 getVars() 函数更改如下

function getVars() {
        var name = document.getElementById("personOne").value;
        if(!isNaN(name) && name.length != 0){
            alert("That is not a valid input. PLease type again!");
        }else{
            person1 = String(document.getElementById("personOne").value);
            age = Number(document.getElementById("ageOne").value);
            firstAdjective = String(document.getElementById("adjective").value);
            document.getElementById("madLibCreation").innerHTML = "There once was a person named " + person1 + ". She was " + age + " and very " + firstAdjective + ".";
        }
    }

https://www.w3.org/WAI/tutorials/forms/validation/ https://www.w3.org/WAI/tutorials/forms/validation/

This link provides some useful information and example code around how you can do this with HTML5, providing the validations and required inputs to each input field.此链接提供了一些关于如何使用 HTML5 执行此操作的有用信息和示例代码,为每个输入字段提供验证和必需的输入。

By implementing these validations your form will not submit until the requirements are met.通过实施这些验证,您的表单在满足要求之前不会提交。

Here are a few other ideas that may also help:以下是一些可能也有帮助的其他想法:

By using a通过使用一个

<form onsubmit="getVars()" name="MadLibs">

tag, your data will be wrapped inside the event, which can be accessed within your submit function.标记,您的数据将被包装在事件中,可以在您的提交函数中访问该事件。 This will also reduce the effort to collect the data via element id's.这也将减少通过元素 ID 收集数据的工作量。

const getVars = function(event) {
    event.preventDefault(); // stop the page refresh on submit
    const formData = event.target; 
    const personOne = formData.personOne;
    ...
}

Lastly by adding tags for each input, it will further increase the accessibility of the form:最后通过为每个输入添加标签,它将进一步增加表单的可访问性:

https://www.w3.org/WAI/tutorials/forms/labels/ https://www.w3.org/WAI/tutorials/forms/labels/

Hope this helps with your project.希望这对您的项目有所帮助。

So you want to prevent wrong information before submitting any thing.所以你要在提交任何东西之前防止错误的信息。 This can be achieved by some checks to the value entered into the fields.这可以通过对字段中输入的值进行一些检查来实现。 This can be done all at once on button click or while typing with an event handler on the field for keyup.这可以在单击按钮或在字段上使用事件处理程序键入以进行键盘输入时一次性完成。 You can further use setTimeout to check with a small delay.您可以进一步使用 setTimeout 来检查一个小的延迟。

If you check and set classes to elements which are faulty, you can check for them with a css selector.如果您检查并将类设置为有问题的元素,您可以使用 css 选择器检查它们。

 const person1 = document.getElementById("personOne") const age = document.getElementById("ageOne") const firstAdjective = document.getElementById("adjective") // use a function(){} block for the handler, it will bin this person1.addEventListener(`keyup`, function(){ // use arrow function to not bind this so it will refer to the html node // can be used to delay the evaluation setTimeout(()=>{ // some regex... /regex/flags will create a new regex // ^ is start, $ is end and [az]* is a to z 0 or more times // flag i is case insensitive const regEx = /^[az]+$/i // if(!regEx.test(person1.value)){ this.classList.add(`invalid`) } else { this.classList.remove(`invalid`) } },200) }) function getVars() { if(!document.querySelectorAll(`.invalid`)[0]){ document.getElementById("madLibCreation").innerText = `There once was a person named ${person1.value} she was ${age.value} and very ${firstAdjective.value}.` } else { alert(`fix your shit`) } }
 .invalid{ color: red; }
 <html> <head> <title> Mad Libs Story </title> <meta charset='utf-8'> <meta name='viewport' content='width=device-width, initial-scale=1'> <link rel='stylesheet' type='text/css' media='screen' href='main.css'> </head> <body> <h3> Welcome to Mad Libs! Please type in the prompted Information. Then press the submit button. Have fun! </h3> <p> Name of Person in Room: <input type="text" id="personOne"> </p> <p> Age: <input type="text" id="ageOne"> </p> <p> Adjective: <input type="text" id="adjective"> </p> <input type="submit" value="Get My MadLib Creation!" onclick="getVars()"> <p id="madLibCreation"></p> </body> <script src="./main.js"></script> </html>

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

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