react-datepicker and react-hooks-form get value displayed in datepicker without time zone - react-datepicker

I am using react-datepicker and react-hook-form. But my picker add time zone to the result:
Is there anyway to ensure that the picker just returns the value provided in the picker with out adding timezone?
const FormDatePicker = props => {
return (
<>
<Label for="exampleEmail">{props.label}</Label>
<Controller
as={
<DatePicker
isClearable
name={props.name}
className={"form-control"}
showTimeSelect
timeFormat="HH:mm"
timeIntervals={15}
timeCaption="time"
dateFormat="dd-MM-yyyy H:mm"
autoComplete="Off"
/>
}
control={props.control}
rules={{ required: false }}
valueName="selected"
onChange={([date]) => date}
name={props.name}
placeholderText="Select date"
defaultValue={null}
/>
</>
);
};

Related

Parameter datetime in asp.net mvc razor erroe with Gregorian

I passing parameters datetime to the controller.
When I pass a hijri date, there's no problem, but when I pass a Gregorian date, the following error appears:
The parameters dictionary contains a null entry for parameter 'DateOfBirth' of non-nullable type 'System.DateTime' for method 'System.Web.Mvc.ActionResult Get_Date_Birth(System.DateTime)' in 'EAMser.Controllers.ExamsAndAdmissionController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
I used this code in the controller:
public ActionResult Get_Date_Birth(DateTime DateOfBirth)
{
if (ModelState.IsValid)
{
ViewBag.Get_B_date = My_code.Get_B_Date(DateOfBirth);
return View("Index");
}
else
return View("Index");
}
And this markup in the view :
<body>
<input type="text" width="120" height="30" id="DateOfBirth1" />
<input type="submit" readonly="readonly" value=" هجري" id="Hdate" />
<input type="submit" value=" ميلادي " id="Gdate" />
#using (Html.BeginForm("Get_Date_Birth", "ExamsAndAdmission", FormMethod.Post))
{
// #Html.Hidden("O_RecId")
#Html.TextBox("DateOfBirth", "", new { #class = "form-control datepicker" })
<input type="submit" readonly="readonly" value=" احسب العمر" />
<hr />
<p>عمر الطالب : </p>
#ViewBag.Get_B_date
}
</body>
<script src="~/Scripts/jquery-3.4.1.js"></script>
<script src="~/Hijri/jquery.calendars.js"></script>
<script src="~/Hijri/jquery.calendars.plus.min.js"></script>
<script src="~/Hijri/jquery.plugin.min.js"></script>
<script src="~/Hijri/jquery.calendars.picker.js"></script>
<script src="~/Hijri/jquery.calendars.picker-ar.js"></script>
<script src="~/Hijri/jquery.calendars.islamic.js"></script>
<script src="~/Hijri/jquery.calendars.ummalqura.js"></script>
<link href="https://cdn.rawgit.com/kbwood/calendars/2.1.0/dist/css/jquery.calendars.picker.css" rel="stylesheet" />
<script type="text/javascript">
$(function () {
$('#Hdate').calendarsPicker({
calendar: $.calendars.instance('ummalqura'),
showOtherMonths: false,
onSelect: function (date) {
$('#DateOfBirth').val(date[0].formatDate());
$('#Hdate').val(" هجري ");
// $("#O_RecId").val(date[0].formatDate());
}
});
$('#Gdate').calendarsPicker({
calendar: $.calendars.instance('gregorian'),
showOtherMonths: false,
showButtonPanel: true,
onSelect: function (date) {
$('#DateOfBirth').val(date[0].formatDate('yyyy/mm/dd'));
$('#Gdate').val(" ميلادي ");
// $("#O_RecId").val(date[0].formatDate());
}
});
});
</script>
How I can I solve this problem?
Thank very much...
I found that the problem is using
<globalization culture="ar-SA" uiCulture="ar-SA" />
The variable datetime gives a null value with the Gregorian date and a valid value with the Hijri date
While when using
<globalization uiCulture="en-US" culture="en-US" />
It gives correct Hijri and Gregorian dates
How can I solve the problem ?
when using
<globalization culture="ar-SA" uiCulture="ar-SA" />
The variable datetime gives a valid value, whether it is the Hijri or Gregorian date
Thank you...

react-hook-form and react-datetime: How to set the time to moment() from a button

I am using react-datetime inside a react-hook-form
I want the user to easily set the time to current time using a button Immediate. Instead of selecting the current time manually.
I am trying the below
const [currentDateTime, setcurrentDateTime] = useState(null);
<Controller
name="resetDateTime"
control={control}
required
render={({ field }) => (
<Datetime
onChange={setcurrentDateTime}
inputProps={{
placeholder: "MM-DD-YYYY HH:mm",
}}
value={currentDateTime}
viewMode="time"
/>
)}
/>
<Button color="primary" className="ml-1" onClick={() => setcurrentDateTime(moment())}>
{"Immediate"}
</Button>
The problem is onSubmit the react-hook-form I get resetDateTime = undefined
How to implement this properly. So I can use the Immediate button and also submit form and get the resetDateTime value
You're mixing RHF with your local state currentDateTime and are not linking the. field to RHF as you're missing to spread the field object to your <Datetime /> component.
The correct way would be to use RHF's setValue to update your resetDateTime field and get rid of the useState hook.
const { control, handleSubmit, setValue } = useForm();
<Controller
name="resetDateTime"
control={control}
required
render={({ field }) => (
<Datetime
{...field}
inputProps={{
placeholder: "MM-DD-YYYY HH:mm",
}}
viewMode="time"
/>
)}
/>
<Button color="primary" className="ml-1" onClick={() => setValue("resetDateTime", moment())}>
{"Immediate"}
</Button>

How do I access data from Form.Item?

export function URLInput() {
const [value, setValue] = useState("");
return (
<Row>
<Col span={24}>
<FloatLabel label="URL" name="url" labelValue={value}>
<Form.Item
hasFeedback
name="url"
rules={[
{
required: true,
min: 5,
type: "url",
whitespace: true,
},
]}
>
<Input
name="url"
onChange={(event) => setValue(event.target.value)}
/>
</Form.Item>
</FloatLabel>
</Col>
</Row>
);
}
I currently have this Form.Item setup.
If there is already a value in url set in the form's initialValues, the Form.Item will magically populate the input field with the value.
However, I want to be able to access this value too so that I can initialize value in
const [value, setValue] = useState("I want to initialize the value here without introducing a props");
How do I do this?
Edit:
The <URLInput> component is actually used inside of a <Form> like this:
<Form
form={form}
onFinish={handleFormSubmit}
initialValues={{ content: content}}
>
<URLInput/>
</Form>
Pass form to URLInput as a prop, then inside URLInput you can access the initialValue url by invoking the following form.getFieldValue('url').
Please see working CodeSandbox example below:
https://codesandbox.io/s/antdform-accessing-formvalues-in-child-formitem-component-uwdb7
Happy coding!

Jquery UI validation error on datepicker date format is always triggered in French

I have a form with a date field. This is how it looks it the Razor view:
#Html.TextBoxFor(model => model.TargetDate, string.Format("{0:D}", Model.TargetDate), new { #class = "datePicker" })
In my JS file, this is how I declare the datepicker:
$.datepicker.setDefaults($.datepicker.regional[Globalize.culture().language]);
$(".datePicker").datepicker({
dateFormat: Globalize.culture().language == "en" ? "DD, MM dd, yy" : "DD dd MM yy",
});
As you can see, the application is multilingual.
When I load the view, the date is displayed properly in the field. But when I try to change the date or submit the form when the application is set in French, a validation error is triggered. This is the generated HTML:
<input class="datePicker hasDatepicker input-validation-error" data-val="true" data-val-date="The field TargetDate must be a date." name="TargetDate" type="text" value="mercredi 16 avril 2014" id="dp1396482596956">
It works well with English.
I'm using the Globalization package along with Jquery-2.1.0 and Jquery-ui-1.10.1.
Any idea on what's causing the validation think it's the wrong format?
I couldn't find any solution to fix the validation so I made a workaround: I added one textbox. The first textbox contains the datepicker date formatted and localized and is not mapped to the viewmodel so validation will be ok. The datepicker updates the second field that is invisible and mapped to the viewmodel with a standard format.
I added an EditorTemplate to my view.
#Html.EditorFor(model => model.TargetDate, "GoalTargetDate")
And this is what my GoalTargetDate.cshtml looks like
#model DateTime?
<span class="date setDate #(Model.HasValue ? string.Empty : "noDisplay")">
#Language.Goals.By
<input class="datePicker" value="#(Model.HasValue ? Model.Value.ToString("D") : string.Empty)" />
#Html.TextBoxFor(model => model, Model.HasValue ? Model.Value.ToString("yyyy-MM-dd") : null, new { #class = "dateValue noDisplay" })
</span>
<span class="date addDate #(Model.HasValue ? "noDisplay" : string.Empty)">Add date</span>
And this is the Jquery code for the datepicker (I have many datepickers in my page)
$.datepicker.setDefaults($.datepicker.regional[Globalize.culture().language]);
$(".datePicker").each(function() {
$(this).datepicker({
dateFormat: Globalize.culture().language == "en" ? "DD, MM dd, yy" : "DD dd MM yy",
altField: $(this).closest(".setDate").find(".dateValue"),
altFormat: "yy-mm-dd"
});
});

Validate on Blur

I've created a JSFiddle to help demonstrate my question: http://jsfiddle.net/jeffreyrswenson/CrYWn/5/
Here's what I'd like to see:
Messages should not appear when page loads.
Messages should appear when submit button is pushed.
Messages should appear after input value is changed and user leaves element. (Tabs or clicks to next field)
Messages should appear after user leave an input without changing.(For example a field is required and the user tabs through the field, but doesn't enter a value. I'd like the validation message to appear when this happens.)
The first four work as I'd expect. Is the last item possible and if so, what do I need to change to enable that behavior?
HTML:
<label>First name:
<input data-bind='value: firstName' />
</label>
<br/>
<label>Last name:
<input data-bind='value: lastName' />
</label>
<br/>
<button type="button" data-bind='click: submit'>Submit</button>
<br/>
<span data-bind='text: errors().length'></span> errors
ViewModel:
var viewModel = function () {
ko.validation.configure({
decorateElement: true,
registerExtenders: true,
messagesOnModified: true,
insertMessages: true,
parseInputAttributes: true,
messageTemplate: null
});
this.firstName = ko.observable().extend({
required: true
});
this.lastName = ko.observable().extend({
required: true,
pattern: {
message: 'Hey this doesnt match my pattern',
params: '^[A-Z0-9]+$'
}
});
this.submit = function () {
if (this.errors().length == 0) {
alert('Thank you.');
} else {
this.errors.showAllMessages();
}
};
this.errors = ko.validation.group(this);
};
You just need to use the standard valueUpdate option of the value binding where you can specify additional events to trigger your property change and with that the validation.
So you just need to add the valueUpdate: "blur" setting on your bindings:
<label>First name:
<input data-bind='value: firstName, valueUpdate: "blur"' />
</label>
<br/>
<label>Last name:
<input data-bind='value: lastName, valueUpdate: "blur"' />
</label>
Demo JSFiddle.
In my case, I needed the value to update after key down because I was making some fields visible if the input had a value. I wanted the underlying value to update but didn't want the validation to show until the user tabbed to the next input.
A bit of CSS and a couple of bindings is what worked for me:
CSS:
div.validationWrapper.standard-focus.has-focus .validationMessage
{
display: none;
}
HTML:
<div class="validationWrapper standard-focus" data-bind="css: { 'has-focus': MyObservableHasFocus() }">
<input class="standard-focus" type="text" data-bind="hasFocus: MyObservableHasFocus, value: MyObservable, valueUpdate: 'afterkeydown'" />
</div>
Knockout:
self.MyObservable = ko.observable('').extend({/* Your validation here */});
self.MyObservableHasFocus = ko.observable(false);
The result is an observable that updates it's value after key up and shows the validation message after it loses focus.

Resources