Adding validation for date forms - javascript

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>

Related

Do form validation in Javascript

I have a form in which I have a field where the user enters their phone number and we force them to start with +34 followed by 9 digits (12 digits in total are what that field should have), but then when I change at +31 for example I pick it up as if it were +34, this is using a
<input type="text">
This is a variable
let phone2 = phone.length
This is the contidion I am using in Javascript
if (phone != '+34' & phone2 < 12) {
evt.preventDefault ();
alert ('The phone number must start with +34 and have at least 12 digits');
}
If anyone can help me
Try this:
Note that onblur means that the test function will fire when the input field loses focus. So, to run the test, type something and then click outside the input field.
const $ = document.querySelector.bind(document);
function test() {
const phone = $('input').value;
if (phone.substr(0, 3) !== '+34' || phone.length < 12) {
alert('The phone number must start with +34 and have at least 12 digits');
} else {
alert('good job');
}
}
<input onblur="test()" placeholder="Phone (must begin with +34)" />

This will not return the "if" statement, even though terms are met

This code should detect where a number is above 1,000,000,000 and below 9,999,999,999. I try to input numbers between these 2 values, but it still returns the else statement. Where is the problem in this code?
<html>
<head>
<title>Checking with RegExp</title>
</head>
<body>
<p>Enter a 10 digit number between 1000000000 and 9999999999.</p>
<textarea id="inputnumber"></textarea>
<button type="button" id="submitnumber">Check</button>
<script>
function checknumber() {
var tendigitnum = document.getElementById("inputnumber")
if (tendigitnum >= 1000000000 && tendigitnum <= 9999999999) {
alert("You entered the number" + tendigitnum + ".")
}
else {
alert("The page will refresh. Please enter a valid number.")
location.reload()
}
}
document.getElementById("submitnumber").onclick = checknumber
</script>
</body>
</html>
You're comparing an HTML element to a number. You want to compare a number to a number, by:
Using the .value property on the element to get the string, and
Parsing that string to a number (you have lots of different ways to do this depending on your use case; see this answer for a list of them)
For instance:
var tendigitnum = Number(document.getElementById("inputnumber").value);
Live Example:
function checknumber() {
var tendigitnum = Number(document.getElementById("inputnumber").value)
if (tendigitnum >= 1000000000 && tendigitnum <= 9999999999) {
alert("You entered the number" + tendigitnum + ".")
} else {
alert("The page will refresh. Please enter a valid number.")
location.reload()
}
}
document.getElementById("submitnumber").onclick = checknumber
<p>Enter a 10 digit number between 1000000000 and 9999999999.</p>
<textarea id="inputnumber"></textarea>
<button type="button" id="submitnumber">Check</button>
On modern browsers you could use a number input:
<input type="number" id="inputnumber">
and use its valueAsNumber property instead of value, since valueAsNumber will already be a number. You can even add the range validation to the input. More on MDN.
You need to check the value in your element, in your code you are checking element

Troubleshooting JS conditional

I've been troubleshooting a form that allows for users to select an amount or select other amount. The other amount when clicked changes the amount to $5. I'm trying to get get it so that if say the user tries to enter a number such as 10, 15 or 20 as examples it will allow them to type it. Currently it is converting anything less than 5 for the starting number to 5 which makes it impossible.
$("#donrAmountInput").on("input", function() {
setDonrAmount("Other");
});
function setDonrAmount(id) {
var amt;
$('#donrAmountButtons .active').removeClass('active');
if (id == "Other") {
amt = $("#donrAmountInput").val() > 5 ? $("#donrAmountInput").val() : 5;
$('#otherAmount button').addClass('active');
}
else {
amt = id.substring(10);
$('#donrAmount' + amt).addClass('active');
}
$('input#donrAmountInput').val(amt);
$('input#donrAmountInput').change();
$('#donrReviewAmount').html(amt);
}
For reference here's the actual form. Help would be greatly appreciated. https://secure.pva.org/site/c.ajIRK9NJLcJ2E/b.9381225/k.8668/FY2016_March_Congressional/apps/ka/sd/donorcustom.asp
You can set your input type to number specify min,max,required attributes and then check the validity of it via javascript/jQuery.
function myFunction() {
var inpObj = $("#id1")[0];
if (inpObj.checkValidity() === false) {
$("#demo").html(inpObj.validationMessage);
} else {
$("#demo").html(inpObj.value);
}
}
$('button').on('click',function(){
myFunction();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="id1" type="number" min="5" max="300" required>
<button>OK</button>
<p id="demo"></p>

What is difference between type=number and type=text in JavaScript regex?

Script have to count 3 chars and filtering anything what isn't a digit.
After any 3 digits, script puts :" - ";
Then prevent from add more than 9 digit.
Anything worked fine, while I use "type=text" in input.
When I using "type=number" (which is important to my new task), script isn't works, well (replace(/(.{3})/g,'$1 - '), puts last 3 chars in input [as I guess]).
My question is:
Is existed difference between both types in regex perspective?
Maybe "type=number" parseing string to int? (but as I know, pure (without JS) "type=number" won't filtering anything in real time).
Ps. Sorry for terrible language.
Now Code:
$(document).ready(function() {
var selection = document.querySelector('.correct_phone input[name=phone]');
//selection.setAttribute('type','number');
selection.addEventListener('input', function(e) {
selection.addEventListener('keydown', function(b) {
if (b.keyCode != 8 && b.keyCode != 46 && b.keyCode != 37 && b.keyCode != 39 && b.keyCode != 16 && b.keyCode != 17 && b.keyCode != 18) {
if (e.target.value.length < 14 && e.target.value.length > 0) {
$(selection).parent('.correct_phone').find('.error_list.not_digit').remove();
//e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{3})/g, '$1 ').trim(); /^\d+$/
e.target.value = e.target.value.replace(/[^\d]/g, '').replace(/(.{3})/g, '$1 - ').trim();
} else if (e.target.value.length > 14) {
$(selection).parent('.correct_phone').find('.error_list.not_digit').remove();
e.target.value = e.target.value.substring(0, e.target.value.length - 1);
$(selection).parent('.correct_phone').css('border-color', 'red').find('label').before("<ul style='margin-bottom:0px;' class='error_list not_digit'><li style=' font-size:1.1em;'>Nuber shuld contains only 9 digits</li></ul>");
$(selection).parent('.correct_phone').find('ul.error_list.not_digit').animate({
opacity: 0
}, 3000, function() {
$(this).remove();
});
}
} else
$(selection).parent('.correct_phone').find('.error_list.not_digit').remove();
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fieldset semi correct_phone">
<label class="input-name">Phone:</label>
<input type="text" name="phone" value="" />
</div>
According to the W3 input type="number" specification, the type="number" is reserved for floating-point numbers.
Specifically the following line describes the bug you're encountering:
The value sanitization algorithm is as follows: If the value of the element is not a valid floating-point number, then set it to the empty string instead.
So in your code you're setting the value of the input to something that is not a floating-point number:
e.target.value = e.target.value.replace(/[^\d]/g, '').replace(/(.{3})/g, '$1 - ').trim();
As that - character is considered as a bad input, the browser follows the specification and sets the value to an empty string.
To fix this, you should use the type="tel", which accepts any valid telephone number as an input:
<input type="tel" name="phone" value="" />
This sets the modern mobile browsers to show numeric keyboard layout (like the type="number".

HTML/Javascript function help for a newbie

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>

Categories

Resources