I want to know how to do form validation in javascript - 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>

Related

Age validation using dd/mm/yyyy

I am trying to validate a form I have for age validating using javascript but it doesn't seem to be working.. not sure why.
Basically the date of birth is entered : dd/mm/yyyy and I need to make sure that in order to submit the form the age of the person is between 15 - 80.. I have tried validating this way but doesn't seem to work.
Html
<label>
Date of birth:
<input type="text" name="birth date" id="DOB"
placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}"
required="required"/>
</label>
Javascript
var birthDate = document.getElementById("DOB").value;
if (2019 - birthDate < 15 || 2019 - birthDate > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
return result;
So, based on your comment, you have a text box as such:
<form>
<input type="text" name="birth date" id="DOB" placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}" required="required"/></label>
</form>
Therefore, document.getElementById("DOB").value; will be of the format dd/mm/yyyy.
So, if you are just checking the year, this should do the trick:
onload = function() {
var form = document.getElementById("form"); //assuming this is your form's ID
form.onsubmit = validate;
}
function checkAge() {
var currentYear = new Date().getFullYear();
var birthDate = document.getElementById("DOB").value;
var errMsg = ""; //this line was missing from my code, and preventing it from working.
//turning "dd/mm/yyyy" into an array of the form { "dd", "mm", "yyyy" }, and taking the "yyyy" part
var birthYear = birthDate.split("/")[2];
var age = currentYear - birthYear;
if (age < 15 || age > 80) {
errMsg =errMsg + "your age must be between 15 and 80\n";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
return false; //form won't submit
}
return true; //form will submit
}
As you can see, I also used getFullYear() so that we don't hard code a fixed current year.
But it would probably be cleaner if you use an <input type="date"> element rather than a text box.
document.getElementById("DOB").value is a string, not a date, so you need to convert it. For that there are different methods; one is to convert the string to YYYY-MM-DD format and pass that to the Date constructor.
Moreover, someone's age changes on their birthday, not at the change of a calendar year, so you need a different logic to get their age. One way is to precalculate the date of 15 years ago and of 81 years ago, and test that the entered birthdate lies between these two extremes.
var DOB = document.getElementById("DOB");
var output = document.getElementById("output");
var go = document.getElementById("go");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Function returns true when age is OK, false otherwise
function check() {
var birthDate = new Date(DOB.value.replace(/(..)\/(..)\/(....)/, "$3-$2-$1"));
return birthDate <= fifteenYearsAgo && birthDate > eightyOneYearsAgo;
}
go.addEventListener("click", function() {
if (check()) {
output.textContent = "Your age is OK";
} else {
output.textContent = "Your age must be between 15 and 80";
}
});
Birthdate: <input id="DOB"><button id="go">Go</button>
<div id="output"></div>
HTML5
If you are certain about your clients having HTML5 support, then use type="date" for your input element, and dynamically set the min and max attributes of a date typed input element and rely on form validation. If the form gets into the submit handler, you can be sure the validations passed:
var DOB = document.getElementById("DOB");
var form = document.querySelector("form");
var fifteenYearsAgo = new Date();
fifteenYearsAgo.setHours(0, 0, 0, 0);
fifteenYearsAgo.setFullYear(fifteenYearsAgo.getFullYear() - 15);
var eightyOneYearsAgo = new Date();
eightyOneYearsAgo.setHours(0, 0, 0, 0);
eightyOneYearsAgo.setFullYear(eightyOneYearsAgo.getFullYear() - 81);
// Border case: in leap years next condition could be false
if ((new Date()).getDate() === eightyOneYearsAgo.getDate()) {
eightyOneYearsAgo.setDate(eightyOneYearsAgo.getDate()+1);
}
DOB.setAttribute("min", eightyOneYearsAgo.toLocaleString("se").slice(0,10));
DOB.setAttribute("max", fifteenYearsAgo.toLocaleString("se").slice(0,10));
form.addEventListener("submit", function(e) {
alert("Your age is OK");
e.preventDefault();
return false;
});
function validationMessage() {
DOB.setCustomValidity("");
const msg = DOB.checkValidity() ? ""
: DOB.validity.valueMissing ? "This field is required"
: DOB.validity.rangeOverflow ? "You must be at least 15"
: DOB.validity.rangeUnderflow ? "You must be at most 80"
: "Enter a valid date"
DOB.setCustomValidity(msg);
}
DOB.addEventListener("input", validationMessage);
validationMessage();
<form>
<label>
Date of birth:
<input type="date" name="birth date" id="DOB" required="required"/>
</label>
<button id="go">Go</button>
</form>
document.getElementById("DOB").value; will give you something like 10/10/2000 and performing arithmetic operations on this string will result in NaN. That must be causing an issue.
Validating date is a more complex than you imagine. There are a lot of things that you need to consider. Use libraries like moment to help you in validating dates.
Edit: Use moment's Difference method to calculate the age.
You can use built in min and max props for input. Try something like this.
<p>Enter a number and click OK:</p>
<input id="id1" type="number" min="15" max="80" required>
<button onclick="myFunction()">OK</button>
<p>If the age is less than 15 or greater than 80, an error message will be
displayed.</p>
<p id="demo"></p>
<script>
function myFunction() {
var inpObj = document.getElementById("id1");
if (!inpObj.checkValidity()) {
document.getElementById("demo").innerHTML = inpObj.validationMessage;
} else {
document.getElementById("demo").innerHTML = "Input OK";
}
}
</script>
Theoretically this should work.
Since you are using pattern and required I assume that you want the error message (if the age is out of range) to be shown to the user in the same way as if the entered date is in the wrong format or is missing. That can be achieved with setCustomValidity.
If you add an event listener of the input event on the DOB-element, you can run a function that checks if the entered age is in rage. It will set the custom error message if the age is out of range, or if the entered date is invalid. Otherwise it let the browser handle the error (if it is missing or of wrong pattern).
function validateDOB(event) {
const minAge = 15, maxAge = 80;
// No custom error message. The broswer will complain if the input isn't in the
// correct form, or if the value is missing since the element has "pattern" and
// and "required".
this.setCustomValidity('');
// Check if there are any other errors
if ( !this.validity.valid ) return;
// Check format of input, and split it into parts
const dobArrayText = this.value.trim().match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
// dobArrayText is null if not in correct format. Let the broswer handle the error.
if (!dobArrayText) return;
// Decode dobArrayText to numeric values that can be used by the Date constructor.
const dob = {
year : +dobArrayText[3],
month : (+dobArrayText[2]) - 1, // month is zero based in date object.
day : +dobArrayText[1]
}
const dobDate = new Date( dob.year, dob.month, dob.day );
// Check validity of date. The date object will accept 2000-99-99 as input and
// adjust the date to 2008-07-08. To prevent that, and make sure the entered
// dobDate is a valid date, I check if the entered date is the same as the parsed date.
if (
!dobDate
|| dob.year !== dobDate.getFullYear()
|| dob.month !== dobDate.getMonth()
|| dob.day != dobDate.getDate()
) {
this.setCustomValidity('Invalid date');
return;
}
// Calc minAgeDate and maxAgeDate
const minAgeDate = new Date(dob.year + minAge, dob.month, dob.day);
const maxAgeDate = new Date(dob.year + maxAge, dob.month, dob.day);
// Get todays date and set Hours, Minutes, Seconds and Milliseconds to 0.
const todayTimestamp = new Date().setHours(0,0,0,0);
// Check validity and set a custom error message if needed.
if ( todayTimestamp < minAgeDate ) {
this.setCustomValidity(`Sorry, you must be older than ${minAge} years old`);
}
else if ( todayTimestamp >= maxAgeDate ) {
this.setCustomValidity(`Sorry, you must be younger than ${maxAge} years old`);
}
}
function formInit() {
document.getElementById('DOB').addEventListener("input", validateDOB);
}
window.addEventListener('DOMContentLoaded', formInit);
<form id="myForm">
<label>
Date of birth:
<input type="text" name="birth_date" id="DOB"
placeholder="dd/mm/yyyy" maxlength="10" pattern="\d{1,2}\/\d{1,2}\/\d{4}"
required="required"/>
</label>
<button type="submit">Submit</button>
</form>

How to validate input date html year?

I want the date input to stop typing once the year has 4 digits. I tried using the min and max component from HTML, but it stills allows you to type erasing the first digit. See example 1.
See example 2 to see that year can be typed with more than 4 digits.
Here are my two test runs, I also tried creating a method with JS using the "onchange" component from HTML and I tried, but none of this seems to work...
https://fiddle.jshell.net/jaelsvd/98xww3qg/9/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Example 1</label>
<input id="date1" type="date" min="1990-12-31" max="2050-12-30">
<br />
<label>Example 2</label>
<input id="date2" type="date" />
Set maxlength and use pattern along with required if you want html5 built in validation:
<form>
<label for ="date2">Example 2</label>
<input id="date2" type="date" pattern="\d{4}" maxlength="4" required />
<button>
Submit
</button>
</form>
For more flexibility, you can use textbox input and check on keypress event, and decide to accept or reject the pressed key like below:
<input type="text" id="my_date" placeholder="MM/dd/YYYY" />
<script>
var myDate = document.querySelector('#my_date');
myDate.onkeypress = function (evt) {
var _evt = evt || windows.event;
var keyCode = _evt.keyCode || _evt.charCode;
var sKey = String.fromCharCode(keyCode);
// TODO: test for key value
// Test for text lenth
var text = this.value;
// TODO: test value, return true to accept, false to reject.
if (text.length > 10) {
alert(text + ' length reach quota.');
return false;
}
else {
return true;
}
};
</script>
For your case, can use :
(1) FormValidation (this link), (2) DateRangePicker - Jquery (this link)
The problem is that the component "date" sets 000's when pressing a key. I had to change the condition and read the 000 before and then set the condition. This worked.
var myDate = document.querySelector('#my_date');
myDate.onkeypress = function (evt) {
var _evt = evt || windows.event;
var keyCode = _evt.keyCode || _evt.charCode;
var sKey = String.fromCharCode(keyCode);
var text = this.value;
var res = text.substring(0, 3);
var res2 = text.substring(0,2);
var res3 = text.substring(0,1);
if(res === "000" || res2 === "00" || res3 ==="0"){
return true;
}else{
if (text.length >= 9) {
return false;
}
else {
return true;
}
}
};
<input type="date" id="my_date" placeholder="MM/dd/YYYY" />

How to clear HTML input tag after alert is generated

I am using the function below to generate an alert when the entered number is not an integer. But I also need to clear the HTML form. I used id.value= ""; but that didn't work. Any suggestions are welcome:
function myFunction(id) {
var x = parseInt(document.getElementById(id).value);
if (!(x === parseInt(x, 10))) {
alert("Empployee ID can be integer numbers only.");
id.value = "";
} else {
}
}
<div class="header1">
<input type="text" id="ename" onblur="myFunction('ename')" name="name" placeholder="Enter Employee ID" required="" />
</div>
Your id.value is not a HTML element. You are trying to get an access to value property of id variable... Something like this "ename".value
Try this:
document.getElementById(id).value = 'VALUE';
function myFunction(id) {
var x = parseInt(document.getElementById(id).value);
if (!(x === parseInt(x, 10))) {
alert("Empployee ID can be integer numbers only.");
document.getElementById(id).value = "";
}
else {
}
}
<div class="header1">
<input type="text" id="ename" onblur="myFunction('ename')" name="name" placeholder="Enter Employee ID" required="" />
</div>
You are setting empty string in the value property of id. id is a string. Hence, it won't work you need to put an empty string somewhere in the document where the id attribute is equal to the function argument.
you need to use :
document.getElementById(id).value = "";
You cannot use id.value
because the id passed in you function was a string.
Since you already passed the id then maybe you can use:
document.getElementById(id).value = "";
Answer Explained

Validating Form Number Type 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);
}

How to change field data from one format to another format

In my form I have four fields. All fields are free to accept numbers and those numbers are converted into predefined character format (I implemented it half with bad logic but in result field it's not combining all field data into some format. Suppose if you type number 2 in every field then result field should look like : 'XXYYZZNN') ,
What I want is :
I will fix a character for each field, for T1 it's ' X ' ,for T2 it's ' Y ',
for T3 it's ' Z ' for T4 it's ' N '
Now
if i enter 2 (it can be 0-9) in T1 the result field should show 'XX'
if i enter 3 in T2 the Result field should show 'XXYYY' (hear XX is previous field data)
if i enter 1 in T3 the Result field should show 'XXYYYZ' and
if i enter 4 in T4 the Result field should show 'XXYYYZNNNN'
like wise final result will be 'XXYYYZNNNN'
How can i do this? Any help will be appreciated. Thanks.
This would be my approach:
Use data attributes to define the character for each input (also use proper label tags and type attributes for inputs)
<div>
<label for="textBox1">T1 :</label>
<input type="text" id="textBox1" data-char="X"></input>
<br/>
<label for="textBox2">T2 :</label>
<input type="text" id="textBox2" data-char="Y"></input>
<br/>
<label for="textBox3">T3 :</label>
<input type="text" id="textBox2" data-char="Z"></input>
<br/>
<label for="textBox4">T4 :</label>
<input type="text" id="textBox3" data-char="N"></input>
<br/>
<label for="message">Result :</label>
<input type="text" id="message"></input>
</div>
Then I would go through all textboxes on every keyup event, parsing their value into a number and appending the corresponding character to the result
$(document).ready(function () {
$('[id^="textBox"]').keyup(function(){
var result = '';
$('[id^="textBox"]').each(function(){
var count = parseInt($(this).val(),10) || 0;
result += Array(count+1).join($(this).data('char'));
});
$('#message').val(result);
});
});
Working fiddle
DEMO
$(document).ready(function () {
function another_format(len,char_code){
var ret='';
for(var i=0;i<len;i++){
ret +=char_code;
}
return $.trim(ret);
}
$("#textBox,#textBox1,#textBox2,#textBox3").keyup(function (event) {
console.log(event.keyCode);
if (event.keyCode >=49 && event.keyCode <= 57 && event.keyCode == 8 && event.keyCode=46) {
var x = another_format($('#textBox').val(),'X');
var y = another_format($('#textBox1').val(),'Y');
var z = another_format($('#textBox2').val(),'Z');
var n = another_format($('#textBox3').val(),'N');
$('#message').val(x+y+z+n);
}
});
});

Categories

Resources