HTML/Javascript function help for a newbie - javascript

So, I am writing a piece of code which checks the month of a number after it has been entered into a textbox, it checks to see if it is a valid number of a month (1-12) and if it is not displays an error message. I get the basic principle of it but i dont get how to run the checking after pressing the button, if you want to help that would be great ! And try and base it om what i already have :p
http://imgur.com/PFjAonf

function myFunction(){
number = document.getElementById('myText').value;
if(isNaN(number)){
alert('Not a valid month');
}else {
if( number > 0 && number <= 12){
alert('valid month');
}else{
alert('Not a valid month');
}
}
}
Month no: <input type="text" id="myText" />
<button onclick="myFunction();">Go</button>

The original, more complete way is:
function myFunction() {
var month = parseInt(document.getElementById('myText').value);
if (typeof month === 'number' && month <= 12 && month > 0) {
alert('yes! valid month! ');
} else {
alert('invalid month! ');
}
}
document.getElementById('myText').value should be a string, and parseInt() convert it to a number.
Update: Use the complete solution, or may cause lots of problems.
However, If you don't want to make it too complicate, just use below code.
function myFunction() {
var month = document.getElementById('myText').value;
if (month <= 12 && month > 0) {
alert('yes! valid month! ');
} else {
alert('invalid month! ');
}
}
<html>
<body>
<title>Month Checker 3000</title>
<h1>Month Checker</h1>
Month Number:
<input type="text" id="myText" />
<button onclick="myFunction()">Go</button>
</body>
</html>

Related

jQuery Greater than and Smaller than check

This is my form:
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
And this my jQuery that's not working:
$('.fms-quote-form').submit(function() {
if ( $('#fms-zip').val() >= 90000 AND <=96162 ) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
How do I (i) check that the value of #fms-zip is greater than 90000 and smaller than 96162 to submit the form, and (ii) redirect the user to another website if any other value is entered?
Look forward to your input :)
Always check the error console - you're assuming syntax that is faulty. AND will be throwing an error - you need &&.
What's more, you can't just specify your higher number and assume JavaScript will know to compare it against the same subject value you compared the lower value against - you have to repeat the subject.
let val = parseInt($('#fms-zip').val());
if (val >= 90000 && val <= 96162 ) { //<-- note 2 references to #val
As #Alessio Cantarella points out, you also need to cast the value to a number - reading the field's value returns a string.
To check if ZIP is greater than 90000 and smaller than 96162, you need to use:
parseInt function to convert #fms-zip's value to an integer
&& logic operator to check that both conditions are valid.
$(function() {
$('.fms-quote-form').submit(function() {
let zip = parseInt($('#fms-zip').val());
let isZipValid = zip >= 90000 && zip <= 96162;
if (isZipValid) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
You can try like this -
$(function() {
$('.fms-quote-form').submit(function() {
var valueZip= parseInt($('#fms-zip').val());
if (valueZip >= 90000 && valueZip <= 96162) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});

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>

Adding validation for date forms

I'm fairly new to javascript, so just looking for a bit of help with adding validation to a form (purely JS/jquery only):
Let's say I have the form getByID("text")
I want to add the validation to stop users entering a decimal place (whole numbers only), no letters or special characters (numbers only), value must not exceed 23 hours/59 minutes (two separate fields for HH:MM (so one must not exceed 23 hours, the other 59 minutes - see below)).
getByID("HH")
must not exceed digit 23 so 0-23 is allowed, no special chars/decimals/letters
getByID("MM")
must not exceed digit 59 so 0-59 is allowed, no special chars/decimals/letters
If anyone could help with this, it would be greatly appreciated. Thanks in advance!
<input type="" name="" id="hh" onkeyup="isNumber(event)" placeholder="HH">
<input type="" name="" id="mm" onkeyup="isNumber(event)" placeholder="MM">
<script type="text/javascript">
function isNumber(evt) {
var id = evt.target.id;
var val = $("#"+id).val();
if (val)
{
var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/;
if(!numericReg.test(val)) {
$("#"+id).val('');
alert('Numeric characters only');
}
else
{
if (id == 'hh')
{
if (val > 24)
{
$("#"+id).val('');
alert('Less than 24');
}
}
if (id == 'mm')
{
if (val > 60)
{
$("#"+id).val('');
alert('Less than 60');
}
}
}
}
}
</script>

Check the length of the number entered in a textbox

I want to write in text box and check if is integer and less than 16 numbers. I have the following JavaScript codes.
<script type="text/javascript">
function doCheck(field) {
if (isNaN(document.getElementById(field).value)) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else {
return true;
}
}
</script>
<form method="post" action="" onsubmit="return doCheck('number');">
national id=<input type="text" name="nat" id="number">
<input type="submit" name="submit">
</form>
document.getElementById(field).value.length
you can find the length of string inside the text box using this
function doCheck(field) {
var len = document.getElementById("number").val().length;
if(parse.Int(document.getElementById(field).value) && len < 16) {
return true;
}
else {
alert('your alert');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
}
be sure you parse it as an integer.
function doCheck(field) {
var input_value = document.getElementById(field).value;
if(isNaN(input_value) || parseInt(input_value,10) != input_value || input_value.length < 16) {
alert('this is not a number');
document.getElementById(field).focus();
document.getElementById(field).select();
return false;
}
else{
return true;
}
}
isNAN() checks whether a number is an illegal number of any type, not only integer. So you have to use something else there, a regular expressions maybe.
To get the length of the field you can simply use:
document.getElementById(field).value.length

javascript validation numerical

Hi sorry i'm still pretty new to javascript.
I've developed a form in HTML and now i'm attempting to add javascript to validate the form.
So far i have simple javascript to make sure each element is filled in,
if (document.order.suburb.value=="")
{
alert("Suburb Cannot Be Empty")
return false
}
if (document.order.postcode.value=="")
{
alert("Postcode Cannot Be Empty")
return false
}
I then have javascript to validate the length of some of the elements,
if (document.order.telephone.value.length < 10)
{
alert("Invalid Telephone Number")
return false
}
Now i'm trying to validate numeric values in the telephone number part but it's not executing correctly, it's like the code is just ignored when it's being executed.
var digits="0123456789"
var temp
var i
for (i = 0 ; i <document.order.telephone.value.length; i++)
{
temp=document.order.telephone.value.substring(i,i+1)
if (digits.indexOf(temp)==-1)
{
alert("Invalid Telephone Number")
return false
}
}
Thanks for reading and thanks for the help :) been stuck on this issue for weeks and have no idea what i'm doing wrong, i tried to code on a separate document with another form and it seemed to work fine.
EDIT
Code for validation for digits in postcode
var post = document.order.postcode.value.replace(white,'');
if(!post){
alert("Post code required !");
return false;
}
post = post.replace(/[^0-9]/g,'');//replace all other than digits
if(!post || 4 > postcode.length) {
alert("Invalid Postcode !");
return false;
}
You may try this example:
var validate = function() {
var white = /\s+/g;//for handling white spaces
var nonDigit = /[^0-9]/g; //for non digits
if(!document.order.suburb.value.replace(white, '')) {
alert("Suburb required !");
return false; //don't allow to submit
}
var post = document.order.postcode.value.replace(white, '')
if(!post) {
alert("Post code required !");
return false;
}
post = post.replace(nonDigit,'');//replace all other than digits
if(!post || 6 > post.length) { //min post code length
alert("Invalid Post code !");
return false;
}
var tel = document.order.telephone.value.replace(white, '');
if(!tel) {
alert("Telephone required !");
return false;
}
tel = tel.replace(nonDigit,'');
if(!tel || 10 > tel.length) {
alert("Invalid Telephone !");
return false;
}
return true; //return true, when above validations have passed
};
<form onsubmit="return validate();" action="#" name="order">
Suburb: <input type="text" id="suburb" name="suburb" ><br/>
Post code: <input type="text" id="postcode" name="postcode"/><br/>
Telephone: <input type="text" id="telephone" name="telephone"/><br/>
<input type="reset"/><input type="submit"/>
</form>
Here is a FIDDLE that will give you something to think about.
You could handle this task in hundreds of ways. I've just used a regex and replaced all of the non-numbers with '' - and compared the length of two variables - if there is anything other than a number the length of the regex variable will be shorter than the unchanged mytelephone.
You can do all kinds of "validation" - just me very specific in how you define "valid".
JS
var mysuburb, mypostcode, mytelephone;
$('.clickme').on('click', function(){
mysuburb = $('.suburb').val();
mypostcode = $('.postcode').val();
mytelephone = $('.telephone').val();
console.log(mysuburb + '--' + mypostcode + '--' + mytelephone);
if(mysuburb.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('Suburb is required');
return false;
}
if(mypostcode.length < 1)
{
$('.errorcode').html('');
$('.errorcode').append('postode is required');
return false;
}
if( mytelephone.length < 1 )
{
$('.errorcode').html('');
$('.errorcode').append('telephone number is required');
return false;
}
if( mytelephone.length != mytelephone.replace(/[^0-9]/g, '').length)
{
$('.errorcode').html('');
$('.errorcode').append('telephone number must contain only numbers');
return false;
}
});

Categories

Resources