Validate date with jquery and help user - javascript

I make a jQuery function which should check user value. The date format what I need is "YYYY-MM-DD". I want to insert "-" in the users text when the length is 5 and 8. What I make:
$(document).ready(function(){
$('input[type=date]').keydown(function(){
var leng = $(this).val().length;
var content = $(this).val();
if(leng == 5){
$(this).text(content+"-");
}else if(leng == 8){
$(this).text(content+"-");
}
});
});
<input type="date" name="openDatePerm1" class="form-control"
id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">
It isn't insert "-" when it should (it do it never). What I do wrong?

You should use $(this).val(content+"-");

You just need to assign by using $(this).val(..), and not $(this).text(..), then just shift your variables by one, so (leng == 4) rather than (leng == 5) and (leng == 7) rather than (leng == 8)
$(document).ready(function(){
$('input[type=date]').keydown(function(){
var leng = $(this).val().length;
console.log(leng)
var content = $(this).val();
if(leng == 4){
$(this).val(content+"-");
}else if(leng == 7){
$(this).val(content+"-");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">

Your solution almost got it right, here a small tweak to yours.
1- the correct function to use is $(this).val(content+"-"); using the function val() not text() as in your example: $(this).text(content+"-");
2- users might need to delete/erase using backspace, then there should be an exception for it. Otherwise the function will keep re-adding the previous content and the user won't be able to delete his input.
3- the number of chars are: 4 and 7 not 5 and 8. Because the first '-' should be inserted after exactly 4 digits e.g. 1999 then '-'. After that the month which is two digits added to the year plus one hyphen 4+1+2 is 7 digits in total.
Here is a working solution:
DEMO
$(document).ready(function() {
$('input[type=date]').keydown(function() {
//Capture the field object
$field = $(this);
//Verify if the user is trying to delete or add new chars
$('html').keyup(function(e) {
if (e.keyCode == 8) {} else {
//alert("here");
//Call the function that will count the chars and add '-'
addDash($field);
}
});
});
function addDash($field) {
var leng = $field.val().length;
var content = $field.val();
if (leng == 4) {
$field.val(content + "-");
} else if (leng == 7) {
$field.val(content + "-");
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10">

make a jQuery function which should check user value. The date format
what I need is "YYYY-MM-DD"
It is not necessary to insert "-" at input type="date" value . If this.checkValidity() returns true , input value should be valid , including "-" between each YYYY , MM , DD . To view resulting string use this.value , to view value as Date string use this.valueAsDate . To make certain that each YYYY , MM , DD are set , try also setting minlength attribute to 10
$(document).ready(function(){
$("input[type=date]").change(function() {
console.log(this.checkValidity(), this.value, this.valueAsDate)
});
});
input[type="date"]:invalid ~ label[for="input"]:after {
color:red;
content:"Invalid date ";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="date" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10" minlength="10"><br>
<label for="input"></label>
Alternatively, using pattern attribute with RegExp
(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))
See HTML5 Pattern - Dates
$(document).ready(function() {
$("input[type=text]").change(function() {
console.log(this.checkValidity(), this.value, this.valueAsDate)
});
});
input[type="text"]:invalid ~ label[for="input"]:after {
color: red;
content: "Invalid date. Required date format: YYYY-MM-DD ";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="openDatePerm1" class="form-control" id="openDatePerm1" placeholder="YYYY-MM-DD" maxlength="10" minlength="10" pattern="(?:19|20)[0-9]{2}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))">
<br>
<label for="input"></label>

Related

Subtract date, month and years dynamically and put data as days using Jquery

I want to subtract a user input years from another input years, but so far I had no luck.
I'll create a snippet where you can play.
What I'm trying to do is to make an input field (A) to enter years only. Then after that select any date and subtract it from the input year (A) (date and month are fixed like 31.03.input_year)...
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = year_enter+'-03-31';
var new_date = $('#new_date').val();
if(year_enter != '') {
//alert(current_year);
}
if(new_date != '') {
//alert(new_date);
var total = new_date - current_year;
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
I always get NaN value, my subtract method is incorrect I guess. I tried using setDate(), getDate() etc, but I don't understand the logic.
Thanks in advance...
You can use new Date() to type cast them into date in order to do arithmetic
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var year_enter = $('#year_select').val();
var current_year = new Date(year_enter + '-03-31');
var new_date = new Date($('#new_date').val());
if (year_enter != '') {
}
if (new_date != '' && year_enter != '') {
if (current_year < new_date) {
$('#answer').val('A must be greater than B');
return;
}
var total = Math.round(Math.abs((current_year.getTime() - new_date.getTime()) / (24*60*60*1000)));
$('#answer').val(total);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001"><span style="opacity: 0.5;"> this currently has fixed -month-day(-03-31) </span>
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
Dates can be tricky to handle, but the moment library makes it a lot easier. In my example I take the input of the two fields, parse them into a moment object and calculate their difference in a duration. You can read more on duration in the Moment.js docs.
The code snippet difference is expressed in days. In case you want to change it to months, or years, update the below line.
log(Math.round(duration.as('days')) + 'days');
You can also include several if statements, to check if the difference is a year, display the result in years. If not, and there's a full month, express the result in months and so on.
Here's a working example in days.
$(document).on('change', '#year_select', function() {
calculate();
});
$(document).on('change', '#new_date', function() {
calculate();
});
function calculate() {
var yearSelect = document.querySelector('#year_select').value;
var newDate = document.querySelector('#new_date').value;
var first_date = new window.moment('31-03-' + yearSelect, 'DD-MM-YYYY');
var second_date = new window.moment(newDate, 'YYYY-MM-DD');
if(yearSelect.length !== 4 || newDate === '') {
log('');
return;
}
var duration = window.moment.duration(first_date.diff(second_date));
log(Math.round(duration.as('days')) + 'days');
}
function log(value) {
var answer = document.querySelector('#answer');
answer.value = value;
}
<script src="https://cdn.jsdelivr.net/momentjs/2.10.6/moment-with-locales.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Enter years (A)</p>
<input type="number" id="year_select" min="0" placeholder="Eg: 2018, 2001">
<br>
<p>Select Date (B)</p>
<input type="date" id="new_date">
<p>(A - B)</p>
<input type="text" readonly id="answer">
NOTE: There are a few discussions out there on how to format a date/duration, e.g. 1 year, 2 months, 5 days. Have a look at a possible solution at these discussions if you want something like this.
How can I format time durations exactly using Moment.js?
How do I use format() on a moment.js duration?

Javascript date validation not working

so i'm trying to validate my date input by using a European format so it can be easily inserted into my database. I'm getting an error message pop up trying to tell me to use the required format however after changing the regular expression about a billion times i still can't seem to get it working.
Below is my JS script that is called when i hit the insert button.
function checkForm(form)
{
// regular expression to match required date format
re = /^(\d{4})-(\d{1,2})-(\d{1,2})/>
if(form.startdate.value != '') {
if(regs = form.startdate.value.match(re)) {
// year value between 1902 and 2017
if(regs[1] < 1902 || regs[1] > (new Date()).getFullYear()) {
alert("Invalid value for year: " + regs[1] + " - must be between 1902 and " + (new Date()).getFullYear());
form.startdate.focus();
return false;
}
// month value between 1 and 12
if(regs[2] < 1 || regs[2] > 12) {
alert("Invalid value for month: " + regs[2]);
form.startdate.focus();
return false;
}
// day value between 1 and 31
if(regs[3] < 1 || regs[3] > 31) {
alert("Invalid value for day: " + regs[3]);
form.startdate.focus();
return false;
}
} else {
alert("Invalid date format: " + form.startdate.value);
form.startdate.focus();
return false;
}
}
}
</script>
This is what calls the insert php file (which deals with the sql side of things) and should called the above JS function. I'm not sure if the error is because i'm also insert a int amount as well as the data within the same submit button.
<form action="insertCarb.php" onsubmit="return checkForm(this)" method="post">
Carb Amount: <input type="text" name="CarbAmount" required/><br>
Date: <input type="text" name="Date" required pattern="/^(\d{4})-(\d{1,2})-(\d{1,2})/" placeholder="yyyy/mm/dd"/><br>
<input type="submit">
</form>
You may change the following code:
<input type="text" name="Date" required pattern="/^(\d{4})-(\d{1,2})-(\d{1,2})/" placeholder="yyyy/mm/dd"/>
To:
<input type="text" name="Date" required pattern="\d{4}-\d{1,2}-\d{1,2}" placeholder="yyyy/mm/dd"/>

How do I put a min and max value in an input text for a custom date

I would like to know how I can add a min value and a max value in my input text for a date.
The format that I would like to have is : dd/mm/yyyy
So I've put a maxlenght to my input and I have added automatically "/" after the user type 2 numbers.
When I test it, everything is fine but I still can write "67/34/8888" and not a correct date for example.
Here's my code :
<form method="post" action="#" id="formStep2">
<input type="text" id="txtDate" class="selector" placeholder="dd/mm/yyyy" maxlength="10" required />
</form>
<script>
$(document).ready(function() {
$("#txtDate").keyup(function(){
if ($(this).val().length == 2){
$(this).val($(this).val() + "/");
}else if ($(this).val().length == 5){
$(this).val($(this).val() + "/");
}
});
});
</script>
Is it possible to add something like :
if ($(this).val().length == 2 && $(this).val().min == 1 && $(this).val().max == 31){...}
Thanks a lot for your help
You should be using type="date":
<input type="date" min="1970-01-01" max="2017-06-08" required>

Replace part of input value on keypress jquery?

For example I have, input type with predefined length.
I want to achieve, when the input value is bigger or equal to 3, to replace that part of string[3] with '/';
<input type="text" id="number" maxlength="6" placeholder="MM/YY"/>
And here is jquery
$('#number').on('keypress',function(){
if(this.value.length <= 3) {
this.value.replace(this.value[3],'/');
}
});
So in short when user types inside input field for example: 1234, the number 3 needs to be replaced with '/' and than the value would be 12/2017, like expiration date of credit card. Thanks in advance
You can try something like this. Had to change the maximum length of input's value from 6 to 7.
Try with e.g. 12/2017.
$('#number').on('keypress', function() {
if (this.value.length >= 2) {
this.value = this.value.slice(0, 2) + '/' + this.value.slice(3, this.value.length)
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="number" maxlength="7" placeholder="MM/YY" />
You could try the following.
Where delimeterIndeces is where in the string you want to check and change the values. InputString is the string returned from the input tag.
let delimeterIndices = [2,5]; // "02[/]15[/]2017";
let inputString = "123152017";
let resultString = inputString.split('').map((char, index) => {
if(delimeterIndices.indexOf(index) !== -1) {
return '/';
} else {
return char;
}
}).join('');
console.log(resultString);

Same function to any numbers of inputs elements javascript

I have multiple elements like this:
<input type="text">
And I want to add slashes (/) so the output is a date mask.
I am using the following function, which only applies on IDs
$(document).ready(function() {
$("#fecha").keyup(function(){
if ($(this).val().length == 2){
$(this).val($(this).val() + "/");
}else if ($(this).val().length == 5){
$(this).val($(this).val() + "/");
}
});
How can i modify the above function to do a date format mask?
Select all input type="text" elements within parent element where keyup event handler should be called on. You can alternatively set a common .className at the elements and use .className selector $(".date")
$(document).ready(function() {
$("#form input[type=text]").keyup(function() {
if (this.value.length == 2) {
$(this).val(this.value + "/");
} else if (this.value.length == 5) {
$(this).val(this.value + "/");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<form id="form">
<input type="text" />
<input type="text" />
</form>

Categories