Validating Form Number Type Javascript - javascript

Hi I've got this problem. In my html code I can't seem to validate my input type "numbers". Iv'e used this code to try and validate it but it does not work
function validateForm()
{
var x=document.forms["form_name"]["number_name"].value;
if (x==null || x=="")
{
alert("The following must be filled out");
return false;
}
}
I took this code from a web site that validates an input type "text" not numbers. I'm trying to implement a working "number" validation to my full html code. Btw this a sample of my form:
<form action = "test.php" method = "post" onsubmit = "return validateForm()" name ="form_name">
<input type = "number" min = "0" placeholder = "0" name = "number_name" size = "2"/>
I am wondering if it is possible to use the javascript valdiation above to validate the number form or is there an easier way to do it.
*In-Depth *
I made a quick html code for my first question and made multiple form of 'number'. It's incomplete... I decide to test one 'number' before implementing the code for the whole form
This is my code so far:
<html>
<head>
<script language="javascript">
function validateForm()
{
var x=document.forms["order"]["cappuccino_qty"].value;
if (x >= 0 || x < 0);
{
alert("The following must be filled out");
return false;
}
}
</script>
<body>
<form action = "test.php" method = "post" onsubmit = "return validateForm()" name ="order">
<label class = "field" for = "Cappucino">Cappuccino
<input type = "number" min = "0" placeholder = "$3.75" name = "cappuccino_qty" size = "2"/><br>
<label class = "field" for = "Espresso">Espresso
<input type = "number" min = "0" placeholder = "$3.00" name = "espresso_qty" size = "2"/><br>
<label class = "field" for = "Double Espresso">Double Espresso
<input type = "number" min = "0" placeholder = "$4.25" name = "double_espresso_qty" size = "2"/><br>
<label class = "field" for = "Flat White">Flat White
<input type = "number" min = "0" placeholder = "$3.75" name = "flat_white_qty" size = "2"/><br>
<label class = "field" for = "Latte">Latte
<input type = "number" min = "0" placeholder = "$3.50" name = "latte_qty" size = "2"/><br>
<label class = "field" for = "Ice Coffee">Ice Coffee
<input type = "number" min = "0" placeholder = "$2.50" name = "ice_qty" size = "2"/><br>
<input type = "submit" value = "submit" name = "submit"/>
<p>
</form>
</body>
</head>
</Html>

Change
if (x==null || x=="")
to
if (/[^\d\.]/.test(x))
That checks for any non-numerical or period characters (assuming you want to allow decimals).
[Edit]
See updated Fiddle: http://jsfiddle.net/5UxGp/1/

A simple way
function validateForm()
{
var x=document.forms["form_name"]["number_name"].value;
if (!(x >= 0) || !(x < 0))
{
alert("The following must be filled out");
return false;
}
}
By the way if 0 is minimum in your form
function validateForm()
{
var x=document.forms["form_name"]["number_name"].value;
if (!(x >= 0))
{
alert("The following must be filled out");
return false;
}
}

You are only testing the variable if it is null or empty but when you input characters on it it jump out on your if statement. Try using this function. See reference here if needed: Validate decimal numbers in JavaScript - IsNumeric(). Hope that helps.
function isNumber(x) {
return !isNaN(parseFloat(x)) && isFinite(x);
}

Related

How do you validate multiple radio buttons at one time without jQuery?

I am writing a validation function for a html code that was given to me for my class, but am not allowed to change the html code besides adding a head and script. I am at such an early stage that I don't know how to use jQuery yet and would like help with validation for the multiple radio buttons.
I have tried looking for the answer on this and many other sites and just can't seem to find it. I have tried multiple codes, but I suspect that all of them were made with jQuery.
The input for the html
<input type = "radio" name = "radNewsletter" value = "" />Health and Wellness<br />
<input type = "radio" name = "radNewsletter" value = "" />Creative Writing<br />
<input type = "radio" name = "radNewsletter" value = ""/>Gardening
The existing validation
function validateForm() {
var x = document.forms["frmNews"]["txtName"].value;
if (x == "") {
alert ("Name must be filled out.");
return false;
}
var y = document.forms["frmNews"]["txtEmail"].value;
if (y == "") {
alert ("Email must be filled out.");
return false;
}
I was unable to get any other output than the form validating when I pressed the submit button, even when the existing validation should have stopped it.
I found that radNewsletter is a common name in your form. In order to validate forms for radio buttons, you can use below code.
function validateForm() {
var radios = document.getElementsByName("radNewsletter");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Must check some option!");
console.log(formValid)
return formValid;
}
<input type = "radio" name = "radNewsletter" value = "" />Health and Wellness<br />
<input type = "radio" name = "radNewsletter" value = "" />Creative Writing<br />
<input type = "radio" name = "radNewsletter" value = ""/>Gardening
<br />
<button onclick="validateForm()">Validate
</button>
function validateForm() {
var radios = document.getElementsByName("radNewsletter");
if(!radios.checked)
{
alert("we are testing")
}
if(radios.checked = true){
alert("your checking the boxs")
}
}
Use document.querySelector and pusedo selector checked. This line document.querySelector('input[name="radNewsletter"]:checked') will give the first radio button with the name radNewsletter which is checked. On click of button check if this value is not null. Hopefully you can validate using this
function validate() {
let isChecked = document.querySelector('input[name="radNewsletter"]:checked');
if (isChecked !== null) {
console.log(isChecked.value);
}
}
<input type="radio" name="radNewsletter" value="hw">Health and Wellness<br />
<input type="radio" name="radNewsletter" value="cw">Creative Writing<br />
<input type="radio" name="radNewsletter" value="g">Gardening<br/>
<button type='button' onclick='validate()'>Validate</button>

User input to make substring

In my program, I have three text fields. In one of them, you are supposed to fill in some text, and in the other two, you fill in two numbers. The text field with the words large number has to have a greater value than the text field with the words smaller number. However, the number has to be less than the length of the user-inputted text.
Whenever I run the program, the javascript console says it cannot read property of sub-string null.
Here are the relevant bits of my code.
<p> Input text, and fill in two numbers in the boxes below. </p>
<p> The number on the left must be smaller than the one on the right</p>
<p> Press on the button to see what happens!
<script type = "text/javascript">
var t = document.getElementById("t");
var s = document.getElementById("small");
var l = document.getElementById("large");
function sub_str() {
var short_str = t.substr(s,l);
var regex_num = /^([0-9]*)$/;
if (l<s) {
window.alert("Please enter a number larger than the smaller number!");
}
if ((regex_num.test(s)) || (regex_num.test(l))){
window.alert("please enter valid numbers!");
} else {
window.alert("Your statement is: " + short_str);
}
}
</script>
<form>
<input type = "text" id = "t"></input> <br />
<input type = "text" id = "small" size = "5">small number</input> <br />
<input type = "text" id = "large" size = "5">large number</input>
<button type = "button" id = "click" onclick = "sub_str()"> Check </button>
</form>
Move DOM element selection into the function, and read its value.
Try this:
<p> Input text, and fill in two numbers in the boxes below. </p>
<p> The number on the left must be smaller than the one on the right</p>
<p> Press on the button to see what happens!
<script type = "text/javascript">
function sub_str() {
var t = document.getElementById("t").value;
var s = document.getElementById("small").value;
var l = document.getElementById("large").value;
var short_str = t.substr(s,l);
var regex_num = /^([0-9]*)$/;
if (l<s) {
window.alert("Please enter a number larger than the smaller number!");
}
if ((!regex_num.test(s)) || (!regex_num.test(l))){
window.alert("please enter valid numbers!");
} else {
window.alert("Your statement is: " + short_str);
}
}
</script>
<form>
<input type = "text" id = "t"></input> <br />
<input type = "text" id = "small" size = "5">small number</input> <br />
<input type = "text" id = "large" size = "5">large number</input>
<button type = "button" id = "click" onclick = "sub_str()"> Check </button>
</form>
There are multiple issues. You are not using .value on your elements to get value and then there is always the chance that your code gets executed before the DOM is loaded. So put your processing inside process() and then use
<body onload="process()">
to invoke this function after the document is loaded.
<script type = "text/javascript">
function process() {
function sub_str() {
var t = document.getElementById("t").value;
var s = document.getElementById("small").value;
var l = document.getElementById("large").value;
var short_str = t.substr(s,l);
var regex_num = /^([0-9]*)$/;
if (l<s) {
window.alert("Please enter a number larger than the smaller number!");
}
if ((regex_num.test(s)) || (regex_num.test(l))){
window.alert("please enter valid numbers!");
} else {
window.alert("Your statement is: " + short_str);
}
}
substr(); // Call the function here
}
</script>
Use the inputs' values, not the inputs themselves
You are interested in what the user typed in your input (that is the input's value), not the input it self. You can get the value of an input by using the input.value property.
Make sure the DOM is loaded when your script is executed
Make sure your DOM is loaded before doing any operation on it (such as getElementById). You should put your script tag at the end of the <body> or wrap your code in an onload handler.
Compare numbers, not strings
Also, when you are doing number comparison, make sure you are actually comparing number and not strings. In JavaScript, "5" > "30" is true (yep...). An input's value is a string. If you want proper number comparison, you must parse the values first (e.g. using parseInt).
console.log('"5" > "30":', "5" > "30");
console.log('5 > 30:', 5 > 30);
console.log('parseInt("5") > parseInt("30"):', parseInt("5") > parseInt("30"));
Fix your tests
The regexp test is wrong (you show an alert when the values are a number instead of when they are not). Moreover, you could just check the result of parseInt instead of regular expression.
Look after your users
Finally, you may also consider using inputs of of type type="number" instead of type="text" for the "small number" and "large number" inputs. type="number" will restrict what can be entered directly in the input itself. It will avoid user errors and the frustration of an alert.
By default, type="number" also add some controls (i.e. 2 arrows to increment or decrement the entry).
Note that even if you set the type to "number", input.value will still be a string that needs to be parsed, but this time, this string will always represent a number.
Similarly, you may programatically and automatically update the "large number" when a user enters a "small number" that is bigger and vice-versa. One less possible error, one less annoying alert.
Your code fixed (without the UI suggestions):
var t = document.getElementById("t");
var s = document.getElementById("small");
var l = document.getElementById("large");
function sub_str() {
var tVal = t.value;
var sVal = parseInt(s.value, 10); // paseInt will return NaN if the string is not a number.
var lVal = parseInt(l.value, 10);
var short_str = tVal.substr(sVal,lVal);
if (lVal<sVal) {
window.alert("Please enter a number larger than the smaller number!");
}
// Typo here, you want to test if the values are *not* a number.
else if (isNaN(sVal) || isNaN(lVal)){
window.alert("please enter valid numbers!");
} else {
window.alert("Your statement is: " + short_str);
}
}
<p> Input text, and fill in two numbers in the boxes below. </p>
<p> The number on the left must be smaller than the one on the right</p>
<p> Press on the button to see what happens!</p>
<form>
<input type = "text" id = "t"></input> <br />
<input type = "text" id = "small" size = "5">small number</input> <br />
<input type = "text" id = "large" size = "5">large number</input>
<button type = "button" id = "click" onclick = "sub_str()"> Check </button>
</form>

I want to know how to do form validation in javascript

I am trying to learn form validation and its not working.
// birthyear must be between 1900 and 2012. turn the birth year textbox color to yellow
window.onload = function() {
document.forms[0].onsubmit = function() {
for(i = 0; i < document.forms[0].elements.length; i++){
var x =
document.forms[birthyear].value
if (x != (>1900 &&<=2012)){
alert("Must be between 1900 and 2012");
x.this.style.color ="yellow";
return false;
//this is how I have created the form:
<form action = "fake.php"></br>
Username
<input class ="required"type = "text" name = "username" id ="username" /><br>
Username
<input class = "required"type = "text" name ="username"id ="username"/> <br>
Birthyear
<input class = "required" type = "number" name = "birthyear" id= "birthyear"/>
<input type = "submit"/>
</form>
if(x<1900 || x> 2012){
alert("invalid year");
Use if statement like this and try
and check the variable x , if it is taking the value user entered correctly.
Simply put alert for x variable and confirm it first
Your if statement condition, x != (>1900 &&<=2012), makes no sense. >1900 and <=2012 do not evaluate to booleans, so you can't use the && operator on them. What you want is something like this:
x<1900 || x>2012
This checks if x is too low or too high, then uses the || (or) operator to check whether x is invalid in either way.
There are some syntax issues with your code.
If you want get value of the birthyear input. You don't have to iterate over elements in form (as you do using for loop), you can do so:
document.forms[0].elements['birthyear']
Also when you get a value of input element it type is string.
And before comparing it to a value with integer type, you should convert string to integer:
intValue = parseInt(stringValue, 10);
So you code will be following
<form action="fake.php">Username
<input class="required" type="text" name="username" id="username" />Birthyear
<input class="required" type="number" name="birthyear" id="birthyear" />
<input type="submit" />
</form>
<script>
// birthyear must be between 1900 and 2012. turn the birth year textbox color to yellow
window.onload = function () {
document.forms[0].onsubmit = function () {
var birthYearElem = document.forms[0].elements['birthyear'],
stringValue = birthYearElem.value,
intValue = parseInt(stringValue, 10);
if (intValue < 1900 || intValue > 2012) {
alert("Must be between 1900 and 2012");
birthYearElem.style.color = "yellow";
return false;
}
}
}
<script>

I need to display a message containing variables (answers from form) after form submit

I need to display the answer from the form in a story. The story must be displayed below the form only after the form is successfully submitted (not an alert), and with the form remaining on the page (not a new page). I am able to insert the form values into the story, but need help with displaying the story after form is submitted. I cannot use anything but html and javascript. I think this can be done with innerHTML.
<head><title>Questions</title>
<script type = "text/javascript" src="quiz1.js">
</script>
</head><body>
<h1>Tell Me About Yourself</h1>
<form name = "the_form" action = "" method = "post"
onSubmit = "var the_result = checkMandatory(); return the_result;">
Full Name:<input type = "text" name = "name" id = "name" /><br/>
Favourite Animal:<input type = "text" name = "animal" id = "animal"><br/>
Favourite Food:<input type = "text" name = "favFood" id = "favFood"><br/>
Favourite Destination:<input type = "text" name = "destination" id = "desitnation"><br/>
Least Favourite Food:<input type = "text" name = "leastFav" id = "leastFav"><br/>
Happiest Moment:<input type = "text" name = "moment" id = "moment"><br/>
Adjective that describes you:<input type = "text" name = "adjective" id = "adjective"><br/>
<br>
<input type="button" value="Submit" onClick = "checkMandatory(); return false;"/><br />
<br />
</form>
<div id="storyDiv"></div>
</body>
</html>
function checkMandatory()
{
// check the text field
// make a var for each question to access easier eg "favMeal"
var name = window.document.the_form.name.value;
//! means 'not'... flips around the if
if (!(name.indexOf(" ") > 0))
{
alert("You must give your full name.");
//return false stops the program
return false;
} else {
//firstName checks all character from 0 to whenever (space) occurs and strips it
var firstName = name.substring(0,name.indexOf(" "));
var name = window.document.the_form.name.value;
var animal = window.document.the_form.animal.value;
var favFood = window.document.the_form.favFood.value;
var destination = window.document.the_form.destination.value;
var leastFav = window.document.the_form.leastFav.value;
var moment = window.document.the_form.moment.value;
var adjective = window.document.the_form.adjective.value;
//alert("first name is " + firstName);
//use alert firstName to test the firstName function
document.write("The young person's name was "+firstName+". "+firstName+" loved to ride
"+animal+
" almost every day. "+firstName+"'s second happiest moment, only next to "+moment+", was in
"+destination+", where "+favFood+
" was served for breakfast, lunch and dinner. It was only when "+firstName+" was told that
"+favFood+
" is actually made from "+animal+", that it instantly became "+firstName+"'s least
favourite food, even worse than "+leastFav+
", and that made "+firstName+" feel very "+adjective+" indeed.")
//document.getElementById('storyDiv').innerHTML = document.getElementById('name').value;
//document.getElementById(‘storyDiv’).innerHTML="The boy's name was "+firstName;
//document.write(‘storyDiv’).innerHTML="The boy's name was " + firstName;
}
}
You can achieve this by posting your form using ajax.
Don't call writethetext(); in your submit button
I'll use jQuery in my solution:
$(function() {
$("form").on("submit", function(e) {
var data = JSON.stringify($("form").serializeArray());
e.preventDefault();
$.post("yourserver/path/", data, function(result) {
writethetext(result);
});
});
});
function checkMandatory() {
// check the text field
// make a var for each question to access easier eg "favMeal"
var name = window.document.the_form.name.value;
//! means 'not'... flips around the if
if (!(name.indexOf(" ") > 0)) {
alert("You must give your full name.");
//return false stops the program
return false;
} else {
//firstName checks all character from 0 to whenever (space) occurs and strips it
var firstName = name.substring(0, name.indexOf(" "));
//alert("first name is " + firstName);
//use alert firstName to test the firstName function
}
}
function writethetext() {
document.getElementById(‘storyDiv’).innerHTML =
("There once was a boy named" + name;)
var firstName = name.substring(0, name.indexOf(" "));
var name = window.document.the_form.name.value;
var animal = window.document.the_form.animal.value;
var favFood = window.document.the_form.favFood.value;
var destination = window.document.the_form.destination.value;
var leastFav = window.document.the_form.leastFav.value;
var moment = window.document.the_form.moment.value;
var adjective = window.document.the_form.adjective.value;
}
function writethetext(text) {
document.getElementById(‘storyDiv’).innerHTML = text;
}
}
<html>
<head>
<title>Questions</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="quiz1.js">
</script>
</head>
<body>
<h1>Tell Me About Yourself</h1>
<form name="the_form" action="" method="post" onSubmit="var the_result = checkMandatory(); return the_result;">
Full Name:
<input type="text" name="name" id="name" />
<br/>Favourite Animal:
<input type="text" name="animal" id="animal">
<br/>Favourite Food:
<input type="text" name="favFood" id="favFood">
<br/>Favourite Destination:
<input type="text" name="destination" id="desitnation">
<br/>Least Favourite Food:
<input type="text" name="leastFav" id="leastFav">
<br/>Happiest Moment:
<input type="text" name="moment" id="moment">
<br/>Adjective that describes you:
<input type="text" name="adjective" id="adjective">
<br/>
<br>
<input type="button" value="Submit" onClick="checkMandatory();
return false;" />
<br />
<br />
</form>
<div id="storyDiv"></div>
</body>
</html>

javascript form validation not doing anything

i am trying to ensure an in put the contents of an input field is within an allowable number of character and if it is not print out an error message after the input field. the bellow js is contained in an external js file.
function validateForm()
{
var err_msg = getElementById('feedback_msg_first_name').value;
var first_name = getElementById('first_name').value;
if(first_name.length < 2)
{
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}
The basic markup
<script type="text/javascript" language="javascript" src="client_form_val.js"></script>
</head>
<body>
<form id="register" name="register" action="includes/register.inc.php" method="post" onsubmit ="return validateForm();">
<label class="label">First Name:</label> <input type="text" name="first_name" id="first_name" /><br />
<span id="feedback_msg_first_name"></span>
the form is simply submitting without anything happening. where an I going wrong? any help would be appreciated.
Have a look at the following http://jsfiddle.net/VL7dc/2/
Rather than explaining where your going wrong, think you need to try and understand why this works and your doesnt.
function validateForm() {
var err_msg = document.getElementById('feedback_msg_first_name');
var first_name = document.getElementById('first_name').value;
if(first_name.length < 2) {
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
} else {
err_msg.innerHTML = '';
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}
You are calling the function when keyup event is fired in form. As a result when a user start typing his/her name after typing a single character this will show the error message.
Instead of calling the function when keyup event is fired, call the function when some button click happens (When the whole first name is typed).
You are forgetting to do document.getElementById. Firebug is giving errors on that
Getting errors:
Uncaught ReferenceError: getElementById is not defined
When you fix the missing documents you get this
Uncaught TypeError: Cannot set property 'innerHTML' of undefined
Reason for the second is this
var err_msg = getElementById('feedback_msg_first_name').value; <-- string
err_msg.innerHTML = 'first name cannot contain less than 2 characters'; <--performing innerHTML on string
Try this
function validateForm()
{
var err_msg = document.getElementById('feedback_msg_first_name');
var first_name = document.getElementById('first_name').value;
if(first_name.length < 2)
{
err_msg.innerHTML = 'first name cannot contain less than 2 characters';
return false;
}
if(first_name.length > 20)
{
err_msg.innerHTML = 'first name cannot contain more than 20 characters';
err_msg.style.color = 'red';
}
}

Categories

Resources