Form Validation - multiple inputs with same class - javascript

I am trying to validate inputs. On this particular page, I have 5 inputs. Three will be selected and all three require numbers. Just for this case, I am only going to check that the user has input a number (there will be more things to validate, but I want to get this right first so I don't repeat myself on multiple pages).
const formE = document.getElementById("SubmissionForm");
const sE = document.getElementById("input1");
const tE = document.getElementById("input2");
formE.addEventListener("click", validate);
function validate(e) {
e.preventDefault();
let valid = true;
if (!sE.value) {
const sError = document.querySelector("showError");
sError.forEach((showError));
sError.setAttribute("aria-hidden", false);
sError.setAttribute("aria-invalid", true);
}
return valid;
}
Now, I am aware this doesn't work with this (I got stuck thinking about a forEach and I just haven't taken it further yet.
In the HTML under the input I have this:
<span role="alert" class="showError" aria-hidden="true"> Please enter a number </span>
Bear in mind, this is just for the number validation I will add other validation points too.
So - what is the correct syntax for the JS to find all the showError classes and make their become visible when the user doesn't put in a number?

There are a lot of ways for that. Basically I can suggest this solution relevant to your question:
const button = document.querySelector('#button');
const number_1 = document.querySelector('#number_1');
const number_2 = document.querySelector('#number_2');
const error = document.querySelector('#error');
button.addEventListener('click',()=>{
if(isNaN(parseInt(number_1.value)) || isNaN(parseInt(number_2.value))){
error.removeAttribute('hidden');
}else{
error.setAttribute('hidden','');
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Validation Demo</title>
</head>
<body>
<input type="text" id="number_1">
<input type="text" id="number_2">
<button id="button">Check them!</button>
<p id="error" hidden>You can type only numbers!</p>
</body>
</html>

Related

Im learning JS and i have a task to make the numbers that i input reverse and pop up in an alert

i made the script that reverses the numbers but i dont know how to make the alert pop up the result of the reversed numbers
I need help to figure this out it probably has a simple solution but i dont know
The code added to snippet is below:
function okreni () { // removed "s" parameter
var a = ' ';
// s = s.toString();
const s = document.getElementById("broj").value.toString();
for (var i = s.length - 1; i>=0; i--) {
a += s[i];
}
window.alert (a);
};
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
</body>
EDIT -
The s = s.toString() has been changed to get the information from the input-value.
alert doesn't display if there's no value to display. in your case you have to passe a value to "okreni()" function.
<button value="okreni" onclick="okreni(**value**)">Okreni</button>
Apparently, you suppose to get the input value as s in okreni(s). However, this is not possible. You have to get the value programatically from the input. Following the working code. I've also created this CodeSandbox for you to try it out:
<!DOCTYPE html>
<html>
<head>`enter code here`
<title>Parcel Sandbox</title>
<meta charset="UTF-8" />
</head>
<body>
<label for="broj">Unesite Broj:</label>
<input type="number" name="broj" id="broj" value="" />
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>
<script type="text/javascript">
function okreni() {
var a = " ";
let inputValue = document.querySelector("#broj").value;
const s = inputValue.toString();
for (var i = s.length - 1; i >= 0; i--) {
a += s[i];
}
window.alert(a);
}
</script>
</body>
</html>
You could also try something like this to reverse your string. In looks much cleaner in my opinion and can even be condensed to a single line if needed.
Apart from that, the reason you are getting an error is because of what alexanderdavide mentioned in his answer. To elaborate further, the okreni function does not require a parameter to be passed. Instead, within the fucntion we look for the value in the input element with the id of broj. So, when you click on the button, the function checks the string in that input, reverses it and then performs an alert.
function okreni() {
let s = document.getElementById('broj').value
s = s.split("").reverse().join("")
window.alert(s)
}
<label for="broj">Unesite Broj:</label>
<input type="text" name="broj" id="broj" value="">
<div>
<button value="okreni" onclick="okreni()">Okreni</button>
</div>

Unpredictable behavior in form validation with regular expressions

I'm completing some exercises from a javascript course (they are only meant for practice, I don't have to send my solutions) and when I'm trying to do a custom validation using regular expressions, capturing the submit event. The problem is that, if I enter an invalid input the first time, sometimes even if I correct it the custom validity message keeps showing up, and the console.log that show how many times the user tried to submit the form doesn't work, as if the submit event didn't even happen (for example: 1st input: "a", 2nd input: "aa", the custom validity message shows up and nothing can be loaded to the console, as if the submit event didn't even happen,but if I enter a valid input the first time, the error dissapears). I don't know if the way to solve this problem is to add an event listener for the blur event of the input and remove the custom validity there if necessary. A part of the code looks something like this (I added changes, the original one was simpler and had even more problems):
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Example of form validation</title>
</head>
<body>
<form>
<fieldset>
<legend>Enter your user data</legend>
<div class="group">
<label for="name">Name</label>
<input id="name" type="text" placeholder="Example: John Doe">
</div>
</fieldset>
<button>Continue</button>
</form>
<script>
let form = document.querySelector("form")
let i = 0
form.addEventListener("submit", function(e){
i++
console.log(`You tried to submit this form ${i} times`)
e.preventDefault()
let input_name = document.querySelector("#name")
let value = input_name.value
let words = [value.split(" ")[0], value.split(" ")[1]]
let words_joined = words[1] ? words[0] + " " + words[1] : words[0] // this ugly conditional statement prevents the program from joining a string with an undefined value
let regex = /^\w{2,}(\s+\w{2,})*$/
let matches = words_joined.match(regex)?.length
try {
if(matches){
handleSuccess.call(input_name)
} else {
let err_msg = `You must enter 1 or 2 words with at least 2 characters each`
input_name.setCustomValidity(err_msg)
throw new Error(err_msg)
}
} catch (err){
handleError.call(form, err) /// I prefer to send to both handlers the apropiate "this"
}
})
function handleError(err){
console.log(err)
}
function handleSuccess(){
this.setCustomValidity(``)
this.classList.add(`success`)
console.log(`The input with the id "${this.id}" is valid`)
this.parentElement.parentElement.parentElement.submit() // submits the form
}
</script>
</body>
</html>```
If I remove the setCustomValidity() function everywhere, the problem dissapears, but that isn't very practical. At least it seems like that is the root of the problem.
Problem solved thanks to the help of Ivar. I made some changes to the original code (those are reflected on the original post, sorry for not posting them anywhere else), and added the following lines:
let value = input_name.value
let words = [value.split(" ")[0], value.split(" ")[1]]
let words_joined = words[1] ? words[0] + " " + words[1] : words[0] // this ugly conditional statement prevents the program from joining a string with an undefined value
// words_joined only contains the first 1 or 2 words
let regex = /^\w{2,}(\s+\w{2,})*$/
let matches = words_joined.match(regex)?.length
try {
if(matches){
value = words_joined // if there were more than 2 words, only the first 2 remain in the value of the input with the id "name"
handleSuccess.call(input_name, "don't submit")
} else {
let err_msg = `You must enter 1 or 2 words with at least 2 characters each`
input_name.setCustomValidity(err_msg)
throw new Error(err_msg)
}
} catch (err){
handleError.call(form, err) /// I prefer to send to both handlers the apropiate "this"
}
})
function handleError(err){
console.log(err)
}
function handleSuccess(shouldSubmit){
this.setCustomValidity(``)
this.classList.add(`success`)
console.log(`The input with the id "${this.id}" is valid`)
if(shouldSubmit != "don't submit") this.parentElement.parentElement.parentElement.submit() // submits the form
}```
the last two functions are almost equal to the ones written in the original question, but with the addition of the "shouldSubmit" parameter and a conditional statement for the last one. Basically, the unpredictability of the error seems to have been caused by how regular expressions with the "g" flag work in js, and it was solved by assigning the return value of the match() function to a variable and using that variable on the rest of the scope. And the main problem, that error showing up even after correcting an invalid input, was ocurring because the custom validity was showing up between submits. Now that an event listener for the "change" event of the input is added, this is corrected. Thanks for the help!

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

Load whole page before javascript runs

I am trying to set the length of an accepted input in the input box by using radio buttons. However every time I try to do this I get 'Uncaught TypeError: Cannot read property 'checked' of null'. After searching I have realised this is because JavaScript elements are loading before the whole HTML code can run. Though I cannot not find any code that is able to load the whole page then run the JavaScript that works for me.
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
<script src= 'card.js'></script>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<button type = 'button' id = 'confirm' onclick = 'proceed()'> Click to proceed </button>
</body>
</html>
I have tried windows.onload but it hasn't worked for me. It is highly likely I wasn't using it right.
var cardLength = 0;
if (document.getElementById('visa').checked || document.getElementById('mastercard').checked) {
cardLength = 16;
} else if (document.getElementById('americanexpress').checked) {
cardLength = 15;
}
function proceed() {
var check = document.getElementById('proceed').value;
if (check == cardLength) {
alert('Proceed')
} else {
alert('Card length invalid')
}
}
You are trying to get element by id 'visa', 'mastercard' and 'americanexpress', but there isn't elements with this id's.
Add id's to your input fields like in the code below.
Also try to include js files at the end of <body> tag.
HTML
<!DOCTYPE html>
<html lang = 'en'>
<meta charset = 'UTF-8'/>
<head>
<h2> Credit Card </h2>
</head>
<body>
<input type = 'radio' name = 'card' value = 'visa' id='visa'> Visa </input>
<input type = 'radio' name = 'card' value = 'mastercard' id='mastercard'> Mastercard </input>
<input type = 'radio' name = 'card' value = 'americanexpress' id='americanexpress'> American Express </input> <br />
<input type = 'number' id = 'cardnumber'/> <br />
<script src= 'card.js'></script>
</body>
</html>
You have multiple issues affecting this.
1) You are correct in that the JS is being loaded before the rest of the HTML. You mentioned that you attempted to use window.onload? Can you please specify how? The following code works:
window.onload = function() {
alert(document.querySelector('[name="card"]:checked').value)
}
Otherwise, I would highly recommend placing your script tag at the bottom of the html, just before the closing </body> tag instead. This has a couple benefits: It loads as you had intended, and it doesn't block the HTML, so to the user, depending on the size of you final script, it loads slightly faster.
2) As lanokvova said, you have no elements with the id of 'visa', 'mastercard', or 'americanexpress'. You can add the ids, or you can use document.querySelector('[name="card"]:checked'), as seen above.
3) You're only running this once on startup. If the user selects a different card, it's not going to update. I would recommend using jQuery for this, as it's significantly cleaner, but it can be done in vanilla JS like so:
document.querySelectorAll('[name="card"]').forEach(function(a) {
a.addEventListener('change', function() {
var selected = this.value;
if(selected === 'visa' || selected === 'mastercard') {
cardLength = 16;
} else if(selected === 'americanexpress') {
cardLength = 15;
}
});
});
A working demo can be found on this Fiddle. You'll just need to update your script to the JS block, and move the tag to the end of the HTML.
Btw, you don't need to close <input> tags, and that <h2> should go inside the body, not the head.

javascript alerts refuse to work in form validation?

i keep trying everything to get these alerts to pop up correctly. i started out using nested functions, then threw them out and put it all in one function, and now when I press enter after filling out any one text box it does nothing at all, just puts the strings in the url, instead of alerting like it was before. I'm not sure if its my function call or anything else because I double checked everything and it all seems to check out to me. here is the entire code that doesnt do anything:
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- VARIABLE DECLARATION -->
f1.city.focus();
function check_form()
{
at_sign = email.search(/#/);
if(document.f1.city.value.length < 1)
{
alert('Please enter a city');
f1.city.focus();
}
else if(document.f1.state.value.length != 2 || !(state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
}
else if(document.f1.zip.value.length != 5 || document.f1.zip.value.isNaN()==true)
{
alert('Please enter a 5 digit zip code');
f1.zip.focus();
}
else if((at_sign<1) || (email.length<3))
{
alert('Please enter a valid email address');
f1.email.focus();
}
else
{
document.write("Form completed");
}
}
</SCRIPT>
</HEAD>
<BODY >
<form name = "f1" action="smartform.html">
<b>City</b>
<input type = "text" name = "city" size = "18" value="" onSubmit = "javascript:check_form()">
<b>State</b>
<input type = "text" name = "state" size = "4" value="" onSubmit = "javascript:check_form()">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5" value="" onSubmit = "javascript:check_form()">
<b>Email</b>
<input type = "text" name = "email" size = "18" value="" onSubmit = "javascript:check_form()">
<input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form()">
</form>
</BODY>
</HTML>
edit: nothing seems to be working that everyone says.. here is my new code:
<html xmlns="http://www.w3.org/1999/xhtml">
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
f1.city.focus();
function check_form(f1)
{
var at_sign = f1.email.search(/#/);
if(f1.city.value.length < 1)
{
alert('Please enter a city');
f1.city.focus();
return false;
}
else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}
else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN()==true))
{
alert('Please enter a 5 digit zip code');
f1.zip.focus();
return false;
}
else if((at_sign<1) || (f1.email.length<3))
{
alert('Please enter a valid email address');
f1.email.focus();
return false;
}
else
{
//document.write("Form completed");
}
return false;
}
</SCRIPT>
</HEAD>
<BODY >
<form name = "f1" onSubmit="return check_form(this)">
<b>City</b>
<input type = "text" name = "city" size = "18" value="">
<b>State</b>
<input type = "text" name = "state" size = "4" value="">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5" value="">
<b>Email</b>
<input type = "text" name = "email" size = "18" value="">
<input type = "submit" name = "button" value = "Done" onclick = "return check_form(this)">
</form>
<b>hi</b>
</BODY>
</HTML>
still get no alerts... i put that hi up and got that.. but no alerts......
alright, I know I should probably be using getElementByID, but my new focus is to find out precisely why my code isn't working. Since my lecture outline examples didnt use this method, I want to figure out why the following code doesnt activate alerts like it used to. I simplified it to this:
<!DOCTYPE html>
<html>
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">
function check_form()
{
document.write("Form started");
var at_sign = document.f1.email.search(/#/);
if(document.f1.city.value.length < 1)
{
alert('Please enter a city');
document.f1.city.focus();
//return false;
}
else if(document.f1.state.value.length != 2 || !(document.f1.state.charCodeAt('0')>=65 && document.f1.state.charCodeAt('0')<=91))
{
alert('Please enter a state in abreviated form');
document.f1.state.focus();
//return false;
}
else if(document.f1.zip.value.length != 5 || isNaN(document.f1.zip.value)==true)
{
alert('Please enter a 5 digit zip code');
document.f1.zip.focus();
//return false;
}
else if((at_sign<1) || (document.f1.email.value.length<3))
{
alert('Please enter a valid email address');
document.f1.email.focus();
//return false;
}
else
{
document.write("Form completed");
}
}
</SCRIPT>
</HEAD>
<BODY onLoad= "javascript:document.f1.city.focus();">
<form name = "f1" action="smartform1.html" onSubmit="javascript:check_form();">
<b>City</b>
<input type = "text" name = "city" size = "18">
<b>State</b>
<input type = "text" name = "state" size = "4">
<b>Zip Code</b>
<input type = "text" name = "zip" size = "5">
<b>Email</b>
<input type = "text" name = "email" size = "18">
<input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form();">
</form>
</BODY>
</HTML>
I get no errors in console, and now when I type something in, I get the test line "form started" to appear for a split second, along with some mysterious error, and then it all disapears and shows the form. but my question is, why doesnt an alert happen along the way to this result? it seems like even if the page got overwritten, it should still pop up. also, is there a way to pause it with code/and or debugging before it gets to the point where its overwritten? so my basic question is: why don't the alerts pop up, and how do I get the alerts to popup and the focus to remain in the correct field where the function left off within the if/else statement?
update 2: i did a quick screen cap of the errors and it turns out f1.email etc were undefined and indeed causing the thing to not work. So I still want to know how to pause it with code or in the debugger, the posts and links didnt exactly seem to be clear 100% on it. once im in the consonle and in debug mode, where exactly do i go from there to let the program pause on error?
also: if I declare the getElementByID variables at the top of my script in the header, then use them in the function, should that work without all the other event handling methods? I'm attempting this as i type.
You should put the submit listener on the form and pass a reference to the form, and return whatever value the function returns, e.g.
<form onsubmit="return check_form(this);" ...>
You should reference the controls as properties of form using their name, don't use the name as a global variable. And declare all variables.
So the function looks like:
function check_form(form) {
var at_sign = email.search(/#/);
if (form.city.value.length < 1) {
alert('Please enter a city');
f1.city.focus();
// cancel submit by returning false
return false;
} else if (form.state.value.length != 2 || !(form.state.charCodeAt(0) >=65 && state.charCodeAt(0)<=91)) {
alert('Please enter a state in abreviated form');
f1.state.focus();
return false;
}
...
}
You should probably be using a regular expression or lookup for validating the state value rather than charCodeAt.
Using document.write after the page has finished loading (e.g. when submitting the form) will erase the entire content of the page before writing the new content.
Edit
Here's what's wrong with your new code:
<SCRIPT LANGUAGE="JavaScript">
Get rid of the language attribute. It's not harmful (well, in a very specific case it might be).
f1.city.focus();
f1 has no been defined or initialised (see comments above about element names and global variables)
function check_form(f1)
{
var at_sign = f1.email.search(/#/);
f1.email is an input element, it has no search property, you can't call it. It does have a value property that is a string, perhaps you meant:
var at_sign = f1.email.value.search(/#/);
Then there is:
else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
again you have forgotten the value property for two of the three expressions, and forgotten to use f1 in the third. You want:
else if(f1.state.value.length != 2 || !(f1.state.value.charCodeAt(0)>=65 && f1.state.value.charCodeAt(0)<=91))
Note that this requires users to enter the state in capital letters, it might help to tell them about that.
Then there is:
else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN() == true))
isNaN is a global variable, not a method of strings. If no value has been entered, then the value is the empty string and isNaN('') returns false. If you want to test that 5 digits have been entered then use:
else if (!/^\d{5}$/test(f1.zip.value))
There is no need to test against true, just use it, nor is there a need to group simple expressions:
else if (f1.zip.value.length != 5 || isNaN(f1.zip.value))
Then finally, if all the test pass:
return false;
that stops the form from submitting. You can omit this return statement, returning undefined will let the form submit. Or return true if you really want.
Ok I want to answer your question but first things first lets walk through your
code and clean it up.
Use this as a template of properly formated code:
<!DOCTYPE html>
<html>
<head>
<title>Smart Form</title>
</head>
<body>
<!-- Code goes here -->
<script type="text/javascript">
</script>
</body>
</html>
Tags & attributes don't need to be capitalized. Javascript comments are like this:
/** Comment. */
Html comments are like this:
<!-- Comment. -->
Also nitpick: attributes should be followed by an equal sign not a space. i.e.
<form name="f1" id="smartForm" action="smartform.html"> ... </form>
Next up proper event binding.
var smartForm = document.getElementById('smartForm');
smartForm.addEventListener('submit', validateForm);
Next up I'm going to teach you how to fish real quick so you can figure out why this was broken for you and how to fix these bugs in the future. Open up the developer console. Evergreen browsers (Chrome, Firefox etc...) have good ones these day. The trick you should know is how to evaluate your code so that you can see if you did something wrong or not in how you're accessing your data. So look up how to open up the developer console in your browser for your platform and type this into your console:
1+1
Should evaluate to: 2.
Next type: document
If you click around you can see that you can walk through the dom a little bit.
Next load up your smartForm app with my changes above and type:
document.getElementById('smartForm')
You should see your element. This is how to properly query objects in the dom.
You'll notice that if you type document.smartForm doesn't work. You should get null, this should tell you that there should be a way to get the element from the document. Hint, it's getElementById. So if you put id's on all your inputs then you can make a list of all the document objects you can query:
var cityElement = document.getElementById('city');
var stateElement = document.getElementById('state');
var zipElement = document.getElementById('zip');
var emailElement = document.getElementById('email');
Next you can start querying the values and such like you were doing:
cityElement.value.length != 2
A cleaned up version would look like this:
<!DOCTYPE html>
<html>
<head>
<title>Smart form</title>
</head>
<body>
<form id='smartForm' action='smartform.html'>
<b>City</b>
<input type="text" id="city" size="18">
<b>State</b>
<input type="text" id="state" size="4">
<b>Zip Code</b>
<input type="text" id="zip" size="5">
<b>Email</b>
<input type="text" id="email" size="18">
<input type="submit" value="done">
</form>
<script type="text/javascript">
var validateForm = function(evt) {
var error = false;
var cityElement = document.getElementById('city');
var stateElement = document.getElementById('state');
var zipElement = document.getElementById('zip');
var emailElement = document.getElementById('email');
if (cityElement.value.length != 2 ||
!(state.charCodeAt(0) >= 65 && state.charCodeAt(0) <= 91)) {
error = true;
alert('oops');
cityElement.focus();
}
// etc..
if (error) {
evt.preventDefault();
}
};
var smartForm = document.getElementById('smartForm');
smartForm.addEventListener('submit', validateForm);
</script>
</body>
</html>
Ok a couple more things I noticed. charCodeAt is for strings only. "hi".chatCodeAt not element.charCodeAt. Also you have this random variable at_sign.
You can save yourself a TON of time and you can learn how to diagnose where the issues are by reading this: https://developer.chrome.com/devtools/docs/console
Learning how to diagnose where the issues are is the single best skill you can learn while trying to get a grapple on javascript. I cannot emphasize this enough, learn how to debug, and you will learn how to program orders of magnitude faster. Trust me, let debugging tutorials be your bread at butter!
Full working example of your code:
http://codepen.io/JAStanton/pen/tjFHn?editors=101
A little less verbose version:
http://codepen.io/JAStanton/pen/iBJAk?editors=101
onSubmit goes in the form, not the inputs, w/o the javascript: Solved =p
<form onsubmit="return check_form();" ...
There are several mishaps in your code that might also cause errors and prevent that from working
Also, check if there are mistakes (like the HTML comment inside script), if an error happens in javascript and is untreated, all javascript in that context stops working. You can check that with any browser debugger (usually F12 will show you a window and display errors if they happen)

Categories