date.parse not sure how to implement - javascript

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

Related

Get value of date input when invalid date

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>

JavaScript regular expression mobile phone number format

1.XXX-XXX-XXXX
2.XXXXXXXXXX
I would like to know the regular expression of the format.
Modifying the existing sources will yield results.
var regExp = /^01([016789]?)-([0-9]{3})-([0-9]{4})$/;
var regExp = /^01([016789]?)[0-9]{3}[0-9]{4}$/;
A statement to check the condition.
I wonder if the contact form is also correct.
var test is a text field that receives input.
if(!regExp.text) {
alert(""phone number format is not valid.");
document.getElementById('phone').focus();
return ;
}
I'm not quite sure what you are trying to achieve, but maybe this example helps:
https://jsfiddle.net/xu9fcbxt/
Notice: jQuery required
Code:
JS:
$(document).ready(function(){
var regExp = /^01[5-7][1-9]-[0-9]{3}-[0-9]{4}/;
$('#phone').focusout(function(){
var text = $('#phone').val();
if(!regExp.test(text)){
alert('not a valid phone number');
}
});
});
HTML:
<input id="phone" type="text" />
This would check if the number has a format like 0151-123-4567

How do I turn a textbox into a date or currency textbox using only JavaScript (jQuery)?

I am trying to build a form using only JavaScript and jQuery. For one of the textboxes, I need to make it display as a date. And another as American Currency.
I have seen a few really cool forms before where it already has the " / /" symbols in there, and as you type the date, it falls perfectly into the symbols so you don't have to type them. Also, I need it to display as a date in the same format (mm/dd/yyyy) when a button is clicked. In addition, somehow, I need it where if no dates were entered, it displays nothing when the button is pushed.
EDIT:
Okay, so, after looking around online, I found a better way to describe what I am looking for for the date. It is exactly the same as the HTML5
<input type="date">
However, after clicking the button, I need it to display as MM/DD/YYYY and the HTML5 only allows YYYY-MM-DD which is NOT what I want.
So, how do I build a single textbox that has the same functions (I don't need the date picker) as the HTML5 "date", but with the display formate as MM/DD/YYYY after a button is clicked?
This sort of input is not trivial. There's some finesse that you'll need to do. First the HTML:
<div id="dateInput">
<input type="number" placeholder="MM" maxlength="2"/>/<input type="number" placeholder="DD" maxlength="2"/>/<input type="number" placeholder="YYYY" maxlength="4"/>
</div>
<div id="moneyInput">
$<input type="number"/>
</div>
Now basic CSS, we'll remove the borders from the inputs and instead add them to the containers:
input{
border:none;
background:transparent;
}
div{
border:1px solid #e0e0e0;
}
Here's the hardest part, the Javascript/jQuery. The money one should work natively but the date one will take some work.
$('#dateInput').on('input', function(){
//get max length of the input
var maxLength = parseInt($(this).attr('maxlength'));
//get the current value of the input
var currentValue = $(this).val();
//if the current value is equal to the maxlength
if(maxLength == currentValue.length){
//move to next field
$(this).next().focus();
};
});
On button press gather all the values from the inputs and display
$('button').on('click', function(e){
e.preventDefault();
//set the variable to append ti
var dateDisplay = '';
//iterate over the inputs
$('#dateInput input').each(function(){
//if dateDisplay exists (will explain soon)
if(dateDisplay && $(this).val() != ''){
//append the value
dateDisplay += $(this).val() + '/';
} else {
//if the value is blank, make the variable false.
dateDisplay = false;
};
});
//now check the variable
if(dateDisplay){
//if it's all good, remove the last character (/) and display
alert(dateDisplay.slice(0,-1));
}
return false;
});
This doesn't check for validity, just handles the general UX.
I was browsing online and in other forums, and found this answer:
$('#date').keyup(function(){
if ($(this).val().length == 2){
$(this).val($(this).val() + "/");
}
else if ($(this).val().length == 5){
$(this).val($(this).val() + "/");
}
});

Validating Data using JS Regex

I am using javascript regex for validating user entered date in format mm/yyyy. I have made regex for this and its working fine, but when I enter ab/abcd its still validating it.
This is my JS and HTML code
function validate() {
var name = document.getElementById("name").value;
var pattern = /\d|\/|\d{4}/;
if (pattern.test(name)) {
alert(name +" has alphanumeric value");
return true;
} else {
alert("Name is not valid.Please input alphanumeric value!");
return false;
}
}
Date: <input type="text" name="name" id="name" />
<input type="submit" value="Check" onclick="validate();"/>
How can I validate the entered date in mm/yyy format,
I am using Jquery DatePicker which allows to select date in this format, and the datepicker also allows manual input. like this Date Picker
Is there any alternate suggestion for this?
Updated:
Try the pattern below instead:
var pattern = /^\d{2}\/\d{4}$/;
See the working code at:
JSFiddle
Another fiddle for extracting the month:
JsFiddle2

onkey event - problem with disabled button

Explanation: At the beginning the value of the field is YYYY-MM-DD. if the user delete the value and doesn't type anything, the button "ok" should be disabled. if the user delete the value and type new value, the button "ok" should be enable. The code is working only for the second case.
function ChangeOkButton()
{
if(document.getElementById('fromDate').value == null)
{ document.getElementById('save').disabled = true; }
else {document.getElementById('save').disabled = false; }
}
<input type="text" name="fromDate" id="fromDate" value="YYYY-MM-DD" onkeypress="ChangeOkButton();"/>
Is this possible?
Thank you!
That function is not very useful for that kind of control, since you could overwrite the value with '12345', 'foobar' or something else different than a realistic value. I suppose you want date starting from 2000-01-01
function ChangeOkButton(field) {
var okbtt = document.getElementById('save');
if ((/^(YYYY\-MM\-DD|2\d{3}\-(0[1-9]|1[0-2])\-(0[1-9]|[12]\{d}|3[01]))$/).test(field.value)) {
okbtt.removeAttribute('disabled');
}
else {
okbtt.disabled = 'disabled';
}
}
and your input is
<input type="text" name="fromDate" id="fromDate" value="YYYY-MM-DD" onkeyup="ChangeOkButton(this);"/>
Please note I've not considered leap years or days per month, this is only a more reliable control on data type entered by the user. Change the regexp as you like
Note: consider to put the 'okbtt' variable outside to the function for a matter of performance, otherwise you need to obtain a reference each time you call this function. awful.

Categories