I am using the jQuery date picker calendar in a form. Once submitted the form passes params along via the url to a third party site. Everything works fine, except for one thing.
If the value inserted into the date field by the datepicker calendar is subsequently deleted, or if the default date, that is in the form on page load, is deleted and the form is submitted I get the following error:
"Conversion from string "" to type 'Date' is not valid."
The solution to my problem is really simple, I want to validate the text field where the date is submitted and send out a default date (current date) if the field is empty for any reason. The problem is I am terrible at Javascript and cannot figure out how to do this.
Here is the form code for my date field.
[var('default_date' = date)]
<input type="text" id="datepicker" name="txtdate" value="[$default_date]" onfocus="if (this.value == '[$default_date]') this.value = '';" onchange="form.BeginDate.value = this.value; form.EndDate.value = this.value;" />
<input type="hidden" name="BeginDate" value="[$default_date]"/>
<input type="hidden" name="EndDate" value="[$default_date]"/>
This is really old and probably solved, but what the heck.
Simplest way to do this is to add a little more javascript to the input's onchange event.
onchange="if( this.value.length > 0 ) { form.BeginDate.value = form.EndDate.value = this.value; } else { form.BeginDate.value = form.EndDate.value = '[$default_date]'; } " />
of course their are still all sorts of other problems associated with date validation, but this is a straightforward way to check for a blank value and return a default based on your current code structure.
Related
i am using an HTML5 input field on a get form to implement search on my site:
<input type="search" name="q" placeholder="search" value="">
everything works, but after the first search the search string the user entered is not saved in the search field, rather the placeholder attribute value is displayed again.
after the first search i would like to have the search string the user entered displayed in the search field on the form.
that means that value attribute of the input field needs to be "" before the first search (so that the placeholder attribute value will display) and then dynamically updated after the first search.
I understand from the Mozilla documentation on <input type="search">
that the value the user entered is stored in the DOMstring "searchTerms = mySearch.value;" but my programming skills and experience are limited.
i am not using php, thank-you in advance.
Try adding this event.preventDefault(); on your function, with that your event will be canceled but the propagation of it won't. If you want to learn more about it, here's the documentation: https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
solved the problem with:
DOMContentLoaded to trigger the javascript
(https://developer.mozilla.org/en-US/docs/Web/API/Window/DOMContentLoaded_event)
URLSearchParams and URLSearchParams.get() to get query string
(https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams)
(https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/get)
getElementById to set value in input field
(https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
it is a common question-
(How can I get query string values in JavaScript?)
<input type="search" name="q" placeholder="search" id=mySearch required value="">
<script type="text/javascript">
window.addEventListener('DOMContentLoaded', (event) => {
let params = new URLSearchParams(document.location.search.substring(1));
let qstring = params.get("q"); // is the string for the query
document.getElementById("mySearch").value = qstring;
});
</script>
I have a form with datetime_local html5 datetime input so that mobile users can use their native datetime picker instead of a jquery substitute which is generally clunkier.
I want the user to be able to select multiple dates.
So far I'm using the onchange trigger to capture the selected datetime and add it to an array. I then try and paste the array into the datetime input so it can be sent with the form.
With one date, it pastes fine, with more than one the input goes blank.
var datearray = [];
$(document).on('change','#mobile_gig_date',function(){
var date = $("#mobile_gig_date").val();
datearray.push(date);
console.log(datearray.join('; '))
$("#mobile_gig_date").val(datearray);
});
The HTML element is;
<input min="2017-09-01T00:00:00" discard_seconds="true" placeholder="Enter the gig date" id="mobile_gig_date" type="datetime-local" name="gig[date]">
Is there a way to add an array to a datetime input, and if so, in what format?
Since your input has the type datetime-local you can't put inside something that is not of that type.
Note that you also tried to put array inside an input - and you can't do this (what you can do is convert your array to string using JSON.stringify and use that value).
I added another hidden input and used it to save the data of your array.
var datearray = [];
$(document).on('change','#mobile_gig_date',function(){
var date = $("#mobile_gig_date").val();
datearray.push(date);
console.log(datearray.join('; '))
$("#mobile_gig_date_temp").val(JSON.stringify(datearray));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input min="2017-09-01T00:00:00" discard_seconds="true" placeholder="Enter the gig date" id="mobile_gig_date" type="datetime-local" name="gig[date]">
<input type="hidden" value="" name="gig[date_temp]" id="mobile_gig_date_temp" />
On my page im working on, are a lot of input-forms.
I want to check the user inputs before submit.
Example
HTML/PHP
<input type="text" name="adress" id="adress">
<input type="text" name="amount" id="amount">
and actually im doing the following in Javascript
Javascript
function dataValidation() {
error=false;
var adress = document.getElementById('adress').value;
var amount = document.getElementById('adress').value;
if (adress == ""){
error=true;
}
if (amount >0 && amount < 999){
}
else {
error=true;
}
if (error == false){
document.forms["myForm"].submit();
}
}
So, basically this works fine for my, but the problem is, i have to create that function for every form, and add a IF for every field
So, im looking for a better solution
Idea 1 : Add a list, wich provides the types of input, like
adress = not empty,
amount = >0 && <999,
and then create a function, which checks all fields with that list
Idea 2: Add a tag or something directly to the input field, what it should contain. and then create a function which checks all the fields
Does somebody have a Idea how this can be done, and would like to help/advise me?
you could try this by jquery as:
your html:
<input type="text" name="adress" id="adress">
<input type="text" name="amount" id="amount">
<input type="button" id="check_input">
and apply jquery for all input field
$("#check_input").click(function() {
$("input").each(function() {
var element = $(this);
if(element.val() == "") {
element.css("border","1px solid red");
element.attr("placeholder","Field is empty");
return false;
}
});
});
if you have multiple forms with same fields try to call validation externally it will reduce some of your work apart from that i dont know any other method so lets wait for others reply
You might wanna consider using HTML5.
HTML5 can save time writing JS validations. For example to validate an email address you could use the following:
<input type="email" name="email" required />
Notice the type="email" and required. Instead of using js for validating, you could use HTML5 form attributes with Regular Expression Patterns.
For example If I want to create an input field which accepts only one numbers and 3 uppercase letters, I can easily do with it using a RegEx pattern:
<input type="text" pattern="[0-9][A-Z]{3}">
Read a little bit more on HTML5 and RegEx. It could help you.
I have a textbox with the property type="date". I am able to retrieve the value in backcode but when I try to assign a value, the placeholder "mm/dd/yyyy" is shown.
When I view the markup, the expected value is there - "value='01/01/1991'". I think it has to do with JavaScript overriding the value.
Any suggestion on how I can work around this?
Edit: Sorry, forgot to include the markup and code
So my markup is
<asp:TextBox ID="txtBirthdate" runat="server" class="form-control input-sm" type="date" onkeypress="handleEnter(event)" />
and c# is
txtBirthdate.Text = usr.BirthDate.ToString("MM/dd/yyyy");
the resulting markup is
<input name="ctl00$ctl00$ctl00$ctl00$Body$Body$Body$Body$txtBirthdate" value="01/20/1991" id="ctl00_ctl00_ctl00_ctl00_Body_Body_Body_Body_txtBirthdate" class="form-control input-sm" type="date" onkeypress="handleEnter(event)">
So as you can see, the value was assigned.
I believe this only happens in Chrome. It requires value assignment to be in "yyyy-MM-dd" format. Try in your C#
txtBirthdate.Text = usr.BirthDate.ToString("yyyy-MM-dd");
This should display the correct value (and it doesn't affect the format of the display).
If will display in this format in other browsers tho. You may want to do some browser detection, e.g.
if (Request.Browser.Browser == "Chrome")
{
txtBirthdate.Text = usr.BirthDate.ToString("yyyy-MM-dd");
} else {
txtBirthdate.Text = usr.BirthDate.ToString("MM/dd/yyyy");
}
but perhaps something more sophisticated
For me this worked:
txtBirthdate.Text = Convert.ToDateTime(TablaHabitacion.Rows[fila].Cells[6].Text).ToString("yyyy-MM-dd");
I have this input code in my form:
<input maxlength="255" id="information_name" name="information[name]" oninvalid="check(this)" placeholder="Nombre Completo" required="required" size="30" style="width:528px;height:25px;" tabindex="3" type="text">
I change the oninvalid message with this javascritp code:
<script>
function check(input) {
if (input.value == "") {
input.setCustomValidity('Debe completar este campo.');
} else {
input.setCustomValidity('Debe corregir este campo.');
}
}
</script>
Here is the problem, if I clicked on submit and the field is empty, the field shome the error so I need to fill the field, but after fill the field, I still getting the warning even the fill is not empty.
What I'm doing wrong???
If you set a value with setCustomValidity() then the field is invalid. That is setting a non-zero length string causes the browser to consider the field invalid. In order to take effects of your new input you have to clear the custom validity.
Simply you can use the following:
<input required maxlength="255" id="information_name" minlength=1 name="information[name]" oninvalid="setCustomValidity('Should not be left empty.')"
oninput="setCustomValidity('')" />
There is no need to use Javascript for this.
You can set a custom validity message with setCustomValidity, however any non-blank string will cause the field to act as if it had an invalid value. You need to setCustomValidity('') to clear the invalidated state of the field.
If your validity is simple and controlled via field attributes, you can use object.willValidate to do the test and set the custom validity message:
oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')"
If you setCustomValidity to any value that is not the empty string then that will cause the input to be in the invalid state. So your condition is checking for a value, then setting the field to be invalid either way. Only setCustomValidity when the value in the field is actually invalid, otherwise set it to an empty string:
<script>
function check(input) {
if (input.value == "") {
input.setCustomValidity('Debe completar este campo.');
} else {
input.setCustomValidity('');
}
}
</script>
For me only oninvalid="this.setCustomValidity(this.willValidate ? '' :'You must choose the account type from the list')" works. There are lots of issues while using it with IE.
The issue is that the custom validity error message needs to be reset to blank/empty again, or the field will never validate (even with correct data).
I use oninvalid to set the custom validity error message, and then use onchange to set the message back to default (blank/empty), and then when the form is checked again it will correctly submit if data was corrected, or it will set the custom error message again if there is problem.
So something like this:
<input type="number" oninvalid="this.setCustomValidity('You need to enter an INTEGER in this field')" onchange="this.setCustomValidity('')" name="int-only" value="0" min="0" step="1">
for React Hooks Typescript users
const inputRef = useRef<HTMLInputElement>(null);
function setCustomValidity(customMsg?: string) {
inputRef.current?.setCustomValidity(
typeof customMsg === 'string' ? '' : t.errors.requiredField,
);
}
<input
ref={inputRef}
onInvalid={() => setCustomValidity()}
onInput={() => setCustomValidity('')}
/>