How to validate input date html year? - javascript

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" />

Related

Search for equal numbers or alphanumeric values inserted in input elements

I want to loop through all the input elements and find if the same value exists.
For example when a user inserts 1(one) and then inserts again the number 1(one), I would like to apply CSS to change the background color of the input element for these 2 equal values or no matter how many they may be.
If the user tries to insert an alphanumerical value then JavaScript handles the code and adds the selected-wrong-input CSS class.
I would like on that element to have a setInterval for 2 seconds and take out the alphanumerical value from the input in order for the user to be able to insert a number again.
I don't mind if the proposed solution is with JavaScript, jQuery or a combination of both.
The html code:
<div class="bus-builder-seat-box-container" id="dynamic-bus-builder-1">
<input id="posA100" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA101" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA102" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA103" type="text" class="input seat_box" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA104" type="text" class="input seat_box selected" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA105" type="text" class="input seat_box selected" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA106" type="text" class="input seat_box selected" onchange="bc.seatBoxHandleEvent(this)">
<input id="posA107" type="text" class="input seat_box selected-wrong-input" onchange="bc.seatBoxHandleEvent(this)">
</div>
The JavaScript code. The first is the event which is called in the html input element onchange
bc.seatBoxHandleEvent = function (el) {
bc.checkInput(el);
var seatNumberFirstFloor = $('#dynamic-bus-builder-1');
if (seatNumberFirstFloor && seatNumberFirstFloor.valueOf()) {
var leftStreaming = (event.target.id);
var rightStreaming = 'posB1' + leftStreaming.substring(5, 7);
document.getElementById(rightStreaming).innerHTML = event.target.value;
}
}
bc.checkInput = function (el) {
let $el = $(el);
var targetValue = event.target.value;
var id = event.target.id;
var classOfInput = event.target.classList;
if (targetValue !== 8 && targetValue !== 0 && (targetValue < 48 || targetValue > 57)) {
console.log('valid number');
console.log(classOfInput);
$(el).toggleClass('selected');
}
else {
console.log('invalid character');
$(el).toggleClass('selected-wrong-input');
//console.log(el.value);
}
var array = new Array(120);
var existsValue = false;
for(var i = 0; i <= array.length; i++) {
console.log(el.value);
console.log(i);
if (el.value === array[i]) {
console.log('hi');
console.log(el.value);
console.log(array[i]);
var existsValue = true;
console.log('existsValue');
console.log('equal number forbidden');
//break;
}
}
I'd suggest to use IsNaN() function to check if the input is a number. Also a keyup event is better for input fields.
var inputList = [];
$('.seat_box').keyup(function(elem){
if(IsNaN(elem.value)) return; //input isn't numeric, add your functionality
if (!valueExists(elem)) inputList.push(elem.value);
else //dublicate value, add functionality
});
function valueExists(elem) {
$(".seat_box").each(function(elem) {
if ($.inArray(this.value, inputList) != -1) return true;
else return false;
});
}

JavaScript form same values

How can I make a form so they cannot repeat the same values in the Input?
I tried a way like:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num1').value;
var textform = [text1,text2];
if (
text1 == text2 ||
text2 == text1
) {
alert("repeated numbers");
return false;
}
But this is gets me into two troubles:
- If I put no value, it will say: Repated Numbers
- If I want to make this for 100 form values, it takes a lot of code
You could give all of your text elements the same class, and grab their values by class name to simplify building the array of text values.
<input type="text" class="checkDupe" id="input1" />
<input type="text" class="checkDupe" id="input2" />
Then grab their values in javascript
var checkDupes = document.getElementsByClassName('checkDupe');
var textArray = [];
for(var i = 0; i < checkDupes.length; i++){
textArray.push(checkDupes[i].value);
}
Now that we have an array of values that they entered, check to see if any of them repeat by sorting the array, and seeing if any two elements side-by-side are the same.
textArray.sort();
var dupes = false;
for(var i = 0; i < textArray.length; i++){
if(textArray[i] === textArray[i + 1]) dupes = true;
}
If we find any duplicates, let the user know.
if(dupes) alert('Repeated numbers!');
You could do something like this:
var text1 = document.getElementById('num1').value;
var text2 = document.getElementById('num2').value;
var textform = [text1, text2];
var seen = {};
textform.forEach(function(value) {
if (seen[value]) {
alert('Bad!');
}
seen[value] = true;
});
In the code above, we loop over each value in the array. The first time we encounter it, we push it into a map. Next time (if) we hit that value, it will exist in the map and it will tell us we've seen it before.
If you give all the input's a common class then you quickly loop through them.
The HTML:
<input type="text" name="num1" class="this that number"></input>
<input type="text" name="num2" class="this number"></input>
<input type="text" name="num3" class="that number"></input>
<input type="text" name="num4" class="number"></input>
<input type="text" name="num5" class=""></input> <!-- we don't want to check this one -->
<input type="text" name="num6" class="number that this"></input>
<input type="text" name="num7" class="this that number"></input>
The JavaScript:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then let the user know they are a bad person
// and stop
if(tracker[inValue])
{
alert("You are a bad person!");
return;
}
// track the value
tracker[inValue] = true;
}
You could also enhance this to let the user know which inputs have duplicate values:
// get all the inputs that have the class numbers
var ins = document.querySelectorAll("input.numbers");
// a tracker to track
var tracker = {};
// loop through all the inputs
for(var i = 0, numIns = ins.length; i < numIns; ++i)
{
// get the value of the input
var inValue = ins[i].value.trim();
// skip if there is no value
if(!inValue) continue;
// if the value is already tracked then error them
if(tracker[inValue])
{
// mark the current input as error
ins[i].className += " error";
// mark the first found instance as an error
ins[tracker[inValue]].className += " error";
}
// save the index so we can get to it later if a duplicate is found
tracker[inValue] = i;
}
Here's a way of doing it that automatically picks up all the text inputs in your document and validates based on what you're looking for. Would be simple enough to expose the valid value and make this the validation handler (or part of one) that handles a form submission.
<meta charset="UTF-8">
<input id="num1" type="text" value="foobar1">
<input id="num2" type="text" value="foobar2">
<input id="num3" type="text" value="foobar3">
<input id="num4" type="text" value="foobar4">
<input id="num5" type="text" value="foobar5">
<button onClick="checkValues();">Validate</button>
<script>
function checkValues() {
var inputs = document.getElementsByTagName('input');
arrInputs = Array.prototype.slice.call(inputs);
var valid = true;
var valueStore = {};
arrInputs.forEach(function(input) {
if (input.type == 'text') {
var value = input.value.toUpperCase();
if (valueStore[value]) {
valid = false;
} else {
valueStore[value] = true;
}
}
});
if (valid) {
alert('Valid: No matching values');
} else {
alert('Invalid: Matching values found!');
}
}
</script>
With jquery you can iterate directly over the inputs.
<form>
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<input type="text" >
<button>
TEST
</button>
</form>
function checkValues(){
var used = {};
var ok = true;
$('form input[type="text"]').each(function(){
var value = $(this).val();
if(value !== ""){
if(used[value] === true){
ok = false;
return false;
}
used[value] = true;
}
});
return ok;
}
$('button').click(function(event){
event.preventDefault();
if(!checkValues()){
alert("repeated numbers");
};
});
https://jsfiddle.net/8mafLu1c/1/
Presumably the inputs are in a form. You can access all form controls via the form's elements collection. The following will check the value of all controls, not just inputs, but can easily be restricted to certain types.
If you want to include radio buttons and checkboxes, check that they're checked before testing their value.
function noDupeValues(form) {
var values = Object.create(null);
return [].every.call(form.elements, function(control){
if (control.value in values && control.value != '') return false;
else return values[control.value] = true;
});
}
<form id="f0" onsubmit="return noDupeValues(this);">
<input name="inp0">
<input name="inp0">
<input name="inp0">
<button>Submit</button>
</form>
For old browsers like IE 8 you'll need a polyfill for every.
You can simply get all inputs iterate them twice to check if they are equals
var inputs = document.getElementsByTagName('input');
for (i = 0; i < inputs.length; i++) {
for (j = i + 1; j < inputs.length; j++) {
if (inputs[i].value === inputs[j].value) {
console.log('value of input: ' + i + ' equals input: ' + j);
}
}
}
<input value="56" />
<input value="12" />
<input value="54" />
<input value="55" />
<input value="12" />

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>

How to add a validation error message next to a field using jQuery

Hi have a form with a few fields. Amongst them:
<div>
<label for="phoneNumber" class="label">Phone Number</label>
<input name="phoneNumber" type="text" id="phoneNumber" size="13" style="float:left;margin-right:10px;">
</div>
<div>
<input type="checkbox" name="activePN" id="activePN" checked >
<label for="activePN">Active</label>
</div>
The, when the form is submited, I want to validate the input and write next to each field for whichever field didn't validate. Like this:
$('#submit').click(function () {
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, '').toString(); //strips non-digits from the string
if (strippedPN.length !== 10) {
$('#phoneNumber').text('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
...
...
...
});
I was hopping that adding those <p> </p> tags would do it. But they don't...
Note: I also tried with html() instead of text() and with activePN instead of phoneNumber.
Use .after().
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
It might be wise to add a class to your p tag too, so you can remove them when the number is edited to be correct.
Try:
$('#submit').click(function(){
var proceed = true;
var strippedPN = $('#phoneNumber').val().replace(/[^\d\.]/g, ''); //strips non-digits from the string - already a String
if(strippedPN.length !== 10){
$('#phoneNumber').after('<p>Phone number has to be 10 digits long.</p>')
proceed = false;
}
}
Its best to use jqueryvalidation plugin.
But in some scenario may be you need to show validation message using custom code, then below may help.
Code
var errorSeen = false;
$('#txtname').keyup(function (e) {
var validInput = false; // TODO set your validation here
if (!validInput) {
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorSeen === false && errorMessageVisible === false) {
$('#txtname').style.borderColor = "red";
$('#txtname').after("<span class='validationMessage' style='color:red;'>
Name is required.</span>");
errorSeen = true;
}
}
else {
$('#txtname').style.borderColor = "";
var errorMessageVisible = $(".validationMessage").is(":visible");
if (errorMessageVisible)
$(".validationMessage").remove();
errorSeen = false;
}
});

Javascript - validation, numbers only

I'm trying to get my login form to only validate if only numbers were inputted. I can it to work if the input is only digits, but when i type any characters after a number, it will still validate etc. 12akf will work. 1am will work. How can i get past this?
Part of the Login
<form name="myForm">
<label for="firstname">Age: </label>
<input name="num" type="text" id="username" size="1">
<input type="submit" value="Login" onclick="return validateForm()">
function validateForm()
{
var z = document.forms["myForm"]["num"].value;
if(!z.match(/^\d+/))
{
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Match against /^\d+$/. $ means "end of line", so any non-digit characters after the initial run of digits will cause the match to fail.
Edit:
RobG wisely suggests the more succinct /\D/.test(z). This operation tests the inverse of what you want. It returns true if the input has any non-numeric characters.
Simply omit the negating ! and use if(/\D/.test(z)).
here is how to validate the input to only accept numbers this will accept numbers like 123123123.41212313
<input type="text"
onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
/>
and this will not accept entering the dot (.), so it will only accept integers
<input type="text"
onkeypress="if ( isNaN( String.fromCharCode(event.keyCode) )) return false;"
/>
this way you will not permit the user to input anything but numbers
This one worked for me :
function validateForm(){
var z = document.forms["myForm"]["num"].value;
if(!/^[0-9]+$/.test(z)){
alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
}
}
Late answer,but may be this will help someone
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
Use will be like
nn=document.forms["myForm"]["num"].value;
ans=isNumber(nn);
if(ans)
{
//only numbers
}
This ans was found from here with huge vote
Validate numbers in JavaScript - IsNumeric()
function validateNumber(e) {
const pattern = /^[0-9]$/;
return pattern.test(e.key )
}
<input name="username" id="username" onkeypress="return validateNumber(event)">
This approach doesn't lock numlock numbers, arrows, home, end buttons and etc
The simplest solution.
Thanks to my partner that gave me this answer.
You can set an onkeypress event on the input textbox like this:
onkeypress="validate(event)"
and then use regular expressions like this:
function validate(evt){
evt.value = evt.value.replace(/[^0-9]/g,"");
}
It will scan and remove any letter or sign different from number in the field.
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
Javascript Approach
onload =function(){
var ele = document.querySelectorAll('.number-only')[0];
ele.onkeypress = function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
return false;
}
ele.onpaste = function(e){
e.preventDefault();
}
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
jQuery Approach
$(function(){
$('.number-only').keypress(function(e) {
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
The above answers are for most common use case - validating input as a number.
But to allow few special cases like
negative numbers & showing the invalid keystrokes to user before
removing it, so below is the code snippet for such special use cases.
$(function(){
$('.number-only').keyup(function(e) {
if(this.value!='-')
while(isNaN(this.value))
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
.split('').reverse().join('');
})
.on("cut copy paste",function(e){
e.preventDefault();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />
Regular expressions are great, but why not just make sure it's a number before trying to do something with it?
function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
if(Number(sum)) {
alert(sum);
} else {
alert("Numbers only, please!");
};
};
function ValidateNumberOnly()
{
if ((event.keyCode < 48 || event.keyCode > 57))
{
event.returnValue = false;
}
}
this function will allow only numbers in the textfield.
I think we do not accept long structure programming we will add everytime shot code see below answer.
<input type="text" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); this.value = this.value.replace(/(\..*)\./g, '$1');" >
Using the form you already have:
var input = document.querySelector('form[name=myForm] #username');
input.onkeyup = function() {
var patterns = /[^0-9]/g;
var caretPos = this.selectionStart;
this.value = input.value.replace(patterns, '');
this.setSelectionRange(caretPos, caretPos);
}
This will delete all non-digits after the key is released.
var elem = document.getElementsByClassName("number-validation"); //use the CLASS in your input field.
for (i = 0; i < elem.length; i++) {
elem[i].addEventListener('keypress', function(event){
var keys = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0];
var validIndex = keys.indexOf(event.charCode);
if(validIndex == -1){
event.preventDefault();
}
});
}
If you are using React, just do:
<input
value={this.state.input}
placeholder="Enter a number"
onChange={e => this.setState({ input: e.target.value.replace(/[^0-9]/g, '') })}
/>
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<script type="text/babel">
class Demo extends React.Component {
state = {
input: '',
}
onChange = e => {
let input = e.target.value.replace(/[^0-9]/g, '');
this.setState({ input });
}
render() {
return (
<div>
<input
value={this.state.input}
placeholder="Enter a number"
onChange={this.onChange}
/>
<br />
<h1>{this.state.input}</h1>
</div>
);
}
}
ReactDOM.render(<Demo />, document.getElementById('root'));
</script>
// I use this jquery it works perfect, just add class nosonly to any textbox that should be numbers only:
$(document).ready(function () {
$(".nosonly").keydown(function (event) {
// Allow only backspace and delete
if (event.keyCode == 46 || event.keyCode == 8) {
// let it happen, don't do anything
}
else {
// Ensure that it is a number and stop the keypress
if (event.keyCode < 48 || event.keyCode > 57) {
alert("Only Numbers Allowed"),event.preventDefault();
}
}
});
});
Avoid symbols like "." "," "+" "-". I tried it and it works fine.
$('#example').keypress(function (evt) {
if (evt != null && evt.originalEvent != null && /\D/.test(evt.originalEvent.key)) {
evt.preventDefault();
evt.stopImmediatePropagation();
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="example" id="example">

Categories

Resources