user12597446
user12597446

Reputation:

Prevent Wrong Input in JS After Submitting A Form

I am creating a sample MabLibs type thing in HTML and JS. When the person inputs stuff in a field, it will use that to create their own 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. 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.

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

Upvotes: 5

Views: 353

Answers (3)

fubar
fubar

Reputation: 383

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.

If you check and set classes to elements which are faulty, you can check for them with a css selector.

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 [a-z]* is a to z 0 or more times
        // flag i is case insensitive
        const regEx = /^[a-z]+$/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>

Upvotes: 0

Nick Taras
Nick Taras

Reputation: 746

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.

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.

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/

Hope this helps with your project.

Upvotes: 0

Madushanka kahawa
Madushanka kahawa

Reputation: 345

For that, you have to check Name field value is number or not. We can check the value is number or not using isNaN function. 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

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 + ".";
        }
    }

Upvotes: 3

Related Questions