Get value of date input when invalid date - javascript

In the jsFiddle, if the input is set to an invalid date, such as 2/31/2000, .val() returns ""
<input type="date" id="date-test" />
<div id="date-label"></div>
$('#date-test').on('change', function() {
var inputDate = $(this).val();
$('#date-label').html(inputDate)
});
As I have read in the comments, this behavior is by design.
Question:
Since I can't check for an empty string, how do I tell when a user has not entered a date vs entering an invalid date?

This got me thinking, so I played around a bit, maybe something like this can help or inspire someone for some other idea...
if you type 02/31/2000 you will get what was typed. But there are obvious problems with this.
And to say, you could also obliviously use some date-picker library, that's what they made for. HTML elements like time and date are very limited, and I don't think that will change any time soon.
let keys = [];
document.onkeypress = function(e) {
e = e || window.event;
console.clear();
keys.push(e.code)
//console.log(keys)
};
$('#date-test').on('input', function() {
let keys2 = [];
keys.forEach(key => {
let key3 = key.split("Digit")
keys2.push(key3[1])
})
$('#date-label').html(keys2)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="date" id="date-test" />
<div id="date-label"></div>

Related

Tabbing to next input using querySelector

I am trying to have the input fields tab over to the next field once maxlength is met but I keep getting an error Failed to execute 'querySelector' on 'Document': 'name=2' is not a valid selector.. Ive read over mozialla's explanation of a querySelector and I've tried using the elements id to focus() on but that gives the same error. I guess Im not understanding how to properly craft a selector to pass to the querySelector.
My Input fields ill only show 2 i have 3:
<Input
onChange={dateChange("month")}
value={date.month}
id="1"
maxLength={2}
type="number"
/>
<span className="sep">/</span>
<Input
onChange={dateChange("day")}
value={date.day}
name="2"
id="2"
maxLength={2}
type="number"
/>
My onChange:
const dateChange = (field) => (e) => {
const fieldIndex = e.target.name;
let fieldIntIndex = parseInt(fieldIndex, 10);
// format to fit
let value = e.target.value;
if (value.length === e.target.maxLength) {
if (fieldIntIndex < 3) {
const nextfield = document.querySelector(
`name=${fieldIntIndex + 1}`
);
console.log(nextfield);
if (nextfield !== null) {
nextfield.focus();
}
}
}
const d = { ...date, [field]: value };
setDate(d);
debounceCallback(handleDateInputChange, d);
};
Im still learning so any advice on this would be great :) thanks in advance!
First of all, I think that it is incorrect to set event listeners like this:
onChange={dateChange("month")}
If you do it that way, you actually execute that function during rendering of the page. The function should be executed when the event occurs. The correct way to do this would be:
onChange={dateChange}
If you also wanted to add parameters to your function then you should do it like this:
onChange={dateChange.bind(this, "month")}
Moreover, regarding the query selector, I think the correct syntax would be:
const nextfield = document.querySelector(`input[name='${fieldIntIndex + 1}']`);
Your name prop is set to an input element, so we use input[name].
Also name has a string value, so we use input[name=''].
Finally we want to set name value parametrically, so we use `input[name='${parameter}']`.
You can find the MDN documentation of bind JavaScript function here and the documentation of querySelector here.
Edit: Another alternative for navigating among inputs would be the tabindex attribute. You can find more about it here.
Name is a string So i think you should do it like this(add brackets)
name='${fieldIntIndex + 1}'

Retain and lose focus on Textbox based on validation

I have a Textbox which will only allow user to input date in mm-dd-yyyy format. If the date is valid, the user will be able to move focus out of the textbox but if it's invalid, the focus should remain inside the textbox until the user corrects it. Currently I am using regex to validate the textbox input and I am able to successfully keep focus inside the textbox in case of invalid date. The issue I am facing is, even when I am correcting the invalid date, the focus does not move out of the textbox.
var dateCheck = function() {
var value = $("#txtbox1").val()
if (/^(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d|3[01])-(19|20)\d{2}$/.test(value)) {
$("#txtbox1").blur();
return true;
}
else {
$("#txtbox1").focus().on('blur', function () {
$(this).focus();
return false;
});
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" size="12" class="form-control" onfocusout="dateCheck()" id="txtbox1"/>
P.S : Using Datepicker is not part of the requirement, would have been much easier I know. Any leads regarding this would be appreciated.
Edit: I have found a working solution and have updated the code above, but this code works only in Chrome and not in IE11
This snipped checks if the date is valid and if it is correctly formatted.
var dateMMDDYYYRegex = "^[0-9]{2}/[0-9]{2}/[0-9]{4}$";
/* isValidData source: http://stackoverflow.com/questions/5812220/how-to-validate-a-date */
function isValidDate(s) {
var bits = s.split('/');
var d = new Date(bits[2], bits[0] - 1, bits[1]);
return d && (d.getMonth() + 1) == bits[0] && d.getDate() == Number(bits[1]);
}
var dateCheck = function() {
var value = $("#txtbox1").val();
if(value.match(dateMMDDYYYRegex) && isValidDate(value)){
$("#txtbox1").blur();
return true;
} else {
$("#txtbox1").focus().on('blur', function () {
$(this).focus();
return false;
});
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<input type="text" size="12" class="form-control" onfocusout="dateCheck()" id="txtbox1"/>
Personally I would consider using an input mask like this one to make it easier for the user to use your code. Also don't forget to validate the date serverside. I would use a libary called Carbon to phrase the date.
Reference to the code: Stackoverflow
You do not need the else part. You can use HTMLElement.blur()
to remove the focus from the element. You can easily pass this element to the function so that you can refer the current element inside the function. I will also suggest you to use oninput event instead of onfocusout.
Try the following way:
var dateCheck = function(el) {
var value = $(el).val();
if (/^(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d|3[01])-(19|20)\d{2}$/.test(value)) {
el.blur();
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" size="12" class="form-control" oninput="dateCheck(this)" id="txtbox1"/>
You could use onblur event, instead of using onfocusout event. Please refer to the following code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
var dateCheck = function () {
var value = $("#txtbox1").val()
if (/^(0[1-9]|1[0-2])-(0[1-9]|1\d|2\d|3[01])-(19|20)\d{2}$/.test(value)) {
$("#txtbox1").blur();
}
else {
$("#txtbox1").focus();
}
};
</script>
<input type="text" size="12" class="form-control" onblur="dateCheck()" id="txtbox1" />
the output as below:

Angular - HTML5 input type "datetime-local" not working with Date Object

I've tried in many ways.
First I get the date as Moment.js object,
this.meeting.start = event.date.local().toDate();
I also tried the following:
this.meeting.start = new Date(this.meeting.start.toLocaleString());
my html:
<input
type="datetime-local"
class="form-control"
value="{{meeting.start}}"
[(ngModel)]="meeting.start" />
but the UI window is empty:"--:-- dd/mm/yy"
Thanks.
This works for me :
let today = new Date();
this.meeting.start = today.toISOString().split('T')[0]
in html
<input
type="date"
class="form-control"
value="{{meeting.start}}"
[(ngModel)]="meeting.start" />
please see example in https://angular-rb5vmu.stackblitz.io (last item : Input Date Format )
Edited!
Based on the help I got here, I managed to get this to work with this workaround:
var add = moment(this.meeting.start).add(3, 'hours');
var result = add.toISOString().split('.')[0];
this.meeting.start = result;
Try this
const fmt = 'HH:mm DD/MM/YY';
const result = moment.utc(this.meeting.start, fmt).local().format(fmt);
Template:
<input type="datetime-local" [value]="result">
Sample StackBlitz
This worked for me, I tried all the answers above but none worked..
// Init dates
let today = moment.utc().local().format('YYYY-MM-DDTHH:mm');
let todayMinus7Days = moment.utc().local().subtract(7, 'days').format('YYYY-MM-DDTHH:mm');
console.log(today);
console.log(todayMinus7Days);
And the result from the browser console is :
And the result is the browser itself is :

how do I know user info submited?

This is what i have http://jsfiddle.net/bd9wv/... what i am trying to do is have boxes users can input numbers in, and be able to comment back based on the numbers they gave..what i have works for one only...if someone would not mind telling me...what holds the input, i think it's var val? i think i should be able to add more boxes. exp... var al id="number1" type="text"/> ...and then in js..... msg = 'Thank you for the wonderful number: ' + (val+al); but that does not work for me. i would like maybe 10 boxes..but 2-3 is good for me to see how it is done. what i am not understanding is what holds the input and how to use it...explaning a little would be great, i think the submit might be getting me. but if you have an example i can look at it an figure it out,i will be very thankful!!
$('#someButton').click(function () {
var val = $('#inputFieldId').val();
var $outputDiv = $('#outputFieldId');
var msg = '';
if (! $.isNumeric(val)) {
msg = 'Please enter a valid number';
}
else if (parseInt(val, 10) > 100) {
msg = 'Enter number less than 100';
}
else {
msg = 'Thank you for the wonderful number: ' + val;
}
$outputDiv.text(msg);
}
Keeping much of your code in place you can make this work. I changed your ID's to classes, since there will be multiple similar elements. I modified a piece of your JS to the following:
var val = $(this).prev(".number").val();
var $outputDiv = $(this).next().next(".feedback");
Using this you can find the closest elements to the input the user was typing.
And your HTML:
Enter number: <input class="number" type="text"/>
<button class="btnNumber">Submit</button>
<br/>
Feedback: <div class="feedback"></div>
Demo: http://jsfiddle.net/bd9wv/1/
I could not understand clearly; but please try whether this work for you or no http://jsfiddle.net/bd9wv/2/
Example:
var val = $(this).parent().find('.number').val();
Here I have used class and have surround the html block with another div

date.parse not sure how to implement

I am looking for some date.parse() help for JavaScript. I have been searching different forums and sites and still have not been able to find a decent example of how to implement this. I am taking a beginning web design class and my instructor has asked for me to do this : "Set the placeholder text for the text box to “Enter a date.” Add an empty paragraph tag set to the document. In a separate JavaScript file code the event handler for the button to set the paragraph text to state whether or not the entered value is a recognizable date format. The Date.parse() method will return a number if passed a valid date string and the special value NaN (not a number) otherwise. NaN can be check for using the built-in function isNaN(). (You may want to refer to your online resources for more information on the Date object, NaN , and isNaN().)" I have been to a ton of websites that show the string but I need a dumbed down example of how to actually use it. here is my html code for the button:
<body>
<form>
<input type="text" id="dateTextInput" size="40" placeholder="Please Enter A Date">
<input type="button" id="addButton" value="Enter a Date">
</form>
<p></p>
</body>
and here is what I have for my .js file:
window.onload = init;
function init() {
var button = document.getElementById("addButton");
button.onclick = handleButtonClick;
}
function handleButtonClick() {
var textInput = document.getElementById("addDateButton");
var dateString = textInput.value;
if (dateString == "") {
alert("Please enter a date");
}
else {
my issue is after my else, if that is even appropriate. I am lost as how to implement the date.parse function. I know it's date.parse(variable) but not sure how to make sure it can be a valid format. Dates can be entered in numerous ways. Should I make an array of possible dates and validate it that way? Or is there a simpler option? A link to a great guide would also be helpful, if an answer cannot be provided here. Thank you for your time.
Update; here is what I am using now. It halfway works. It alerts for an empty set. I just can't get the parse to alert:
function handleButtonClick() {
var textInput = document.getElementById("dateTextInput");
var dateString = textInput.value;
var dateValue = Date.parse(dateString);
var valid = !isNaN(dateValue);
if (dateString == "") {
alert("Please enter a date");
} else {
return(valid);
}
}
I hope everthing is understandable.
<form id="dateForm">
<!-- pattern just allow such format X.X.XXXX Or XX.XX.XXXX Or X.XX.XXXX Or XX.X.XXXX -->
<input type="text" id="dateTextInput" size="40" pattern="^\d{1,2}.\d{1,2}.\d{4,4}$" placeholder="Please Enter A Date">
<input type="submit" id="addButton" value="Enter a Date">
</form>
<script>
// onsubmit ist just called when dateTextInput is empty or has got valid date
document.getElementById('dateForm').onsubmit = function(e){
e.preventDefault(); // avoid to reload page
var date = document.getElementById('dateTextInput').value;
if(date === ''){ // always use === because == is sometimes buggy
alert('Please enter a date');
}
else{
var convertedDate = date.split('.'); // -> ['03','06','1985']
convertedDate = new Date(convertedDate[2],convertedDate[1],convertedDate[0]);
console.log(convertedDate.getTime()); // I think you wanted to get Milliseconds, but this works just as well
}
return false;
};
</script>
When the order of the day, month and year is not right, then just edit the pattern of the input-field and this codeline:
convertedDate = new Date(convertedDate[2],convertedDate[1],convertedDate[0]);
Dates can be entered in numerous ways. Should I make an array of possible dates and validate it that way?
No array. You should just accept what Date.parse does accept:
whether the entered value is a recognizable date format. The Date.parse() method will return a number if passed a valid date string and NaN otherwise.
"recognizable" does refer to Date.parse capatibilites I'd say. It's trivial to implement then:
var dateValue = Date.parse(dateString);
var valid = !isNaN(dateValue);
// grab the paragraph
if (valid)
// set the paragraph text accordingly
else
// output something different

Categories