简体   繁体   English

在提交按钮之前如何验证数据?

[英]How to validate data before button submit?

I have this code jsFiddle . 我有这段代码jsFiddle What I'm trying to accomplish is the following. 我想要完成的是以下内容。 As the user clicks the 'Ok' button inside the dialog, I want the code to compute whether the date at 'field1' is after 'field2', meaning, the current period is after the previous (as it should). 当用户单击对话框中的“确定”按钮时,我希望代码计算“ field1”的日期是否在“ field2”之后,这意味着当前时间段是在前一个时间段之后(应如此)。 If this is so, I want the action to continue, populate the textboxes and close the dialog. 如果是这样,我希望操作继续,填充文本框并关闭对话框。 Whenever that is not true, I want to alert the user that the selections made, were invalid (Previous cannot come after Current). 每当不正确时,我都想提醒用户所做的选择是无效的(Previous不能在Current之后)。 I do not have a problem with the date math (the plugin date.js makes it easy enough), I am having problems when it comes to trying to figure out where to include this condition. 我对日期数学没有任何问题(插件date.js使其简单易用),在尝试弄清楚该条件包括在哪里时,我遇到了问题。 Any help will be appreciated, feel free to change the code and post your results here. 任何帮助将不胜感激,随时更改代码并在此处发布结果。 Thanks. 谢谢。

I have a feeling the code should go just before closing the dialog, but I cannot get the right conditions to make it so, eg: 我觉得代码应该在关闭对话框之前执行,但是我无法获得正确的条件,例如:

//code up to here handles 'if's and 'else's
var currentPeriod = $("input#field1").val()
var previousPeriod = $("input#field2").val()

 d1 = Date.parse(currentPeriod);
 d2 = Date.parse(previousPeriod); 

if((Date.compare(d1,d2))=='1')
{
  $(this).dialog("close");
 }
else
  {
   alert("Invalid date range");
 }

What you wrote above, using Date.compare() is mostly correct. 您上面编写的内容,使用Date.compare()基本上是正确的。 Documentation on the compare is here . 比较文件在这里

There are two points on it though: 尽管有两点:

  • That code isn't anywhere in the fiddle you put together. 该代码不在您摆弄的小提琴中的任何地方。
  • In your fiddle $("input#field1") and #("input#field2") would refer to the input boxes, not the dialog select boxes. 在您的小提琴中, $("input#field1")#("input#field2")将引用输入框,而不是对话框选择框。 You want to do the validation before you assign the values to the input boxes, otherwise you close the dialog and it doesn't matter as the values are already assigned. 您需要在将值分配给输入框之前进行验证,否则请关闭对话框,因为已分配值并不重要。

Where it should go (based on the fiddle) is at the beginning of the function that gets called when the the OK button is clicked. 它应该去的位置(基于小提琴)是在单击“确定”按钮时调用的函数的开头。 Right now it looks like you're doing handling the current date and putting the value in the input boxes, then handling the previous date and assigning the values. 现在看来,您正在处理当前日期并将值放在输入框中,然后处理上一个日期并分配值。 You would need to check if the values are before one another before any of this happened. 您需要先检查这些值是否在其他值之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM