如何触发验证

问题描述 投票:0回答:4

在按“显示”按钮之前,如何强制用户输入有效时间和有效数字?

我的html代码中有两个字段,我在JS中找到了两个很好的验证脚本。一个用于时间,一个用于确定输入字段是否具有数值。

我无法改变HTML中的任何内容。

function checkTime() {
  re = /^\d{1,2}:\d{2}([ap]m)?$/;
  if (time_untilopt.value != '' && !time_untilopt.value.match(re)) {
    alert("Wrong time!");
    return false;
  }
}

function checkRoomNr() {
  var numbers = /^[0-9]+$/;
  if (roomopt.value.match(numbers)) {
    console.log("is number");
  } else {
    console.log("not a number!");
  }
}
<div>
  <label for="time-until">Time</label>
  <input type="text" id="time-until">
</div>
<div>
  <label for="room">Room</label>
  <input type="text" id="room">
</div>
<button id="show-schedule">Show</button>
javascript html
4个回答
0
投票

如果要在将数据输入字段时进行验证,则应将函数设置为在字段的input事件上运行。如果要等到用户离开该字段并更改了字段的值,则可以使用字段的change事件。

但是,您还希望在提交包含字段的表单时检查数据,因此您还需要为表单设置submit事件处理程序。

将函数连接到事件的方法是将函数注册为“事件处理程序”,并使用.addEventListener()方法完成(使用基于现代标准的代码):

// First, get references to the elements you'll want to work with.
// And, use those variable names to reference the elements in your 
// code, not their IDs.
var timeUntil = document.getElementById("time-until");
var room = document.getElementById("room");
var form = document.querySelector("form");

// We'll set up a variable to keep track of whether there are any errors
// and we'll assume that there are not any initially
var valid = true; 

// Set up the event handling functions:
timeUntil.addEventListener("change", checkTime);
room.addEventListener("change", checkRoomNr);
form.addEventListener("submit", validate);

function checkTime(evt){
  re = /^\d{1,2}:\d{2}([ap]m)?$/;
  if(timeUntil.value != '' && !timeUntil.value.match(re)) {
    console.log("Wrong time!");
    valid = false; // Indicate an error
  } else {
    valid = true;
  }
}

function checkRoomNr(evt){
  var numbers = /^[0-9]+$/;
  if(!room.value.match(numbers)){
    console.log ("not a number!");
    valid = false; // Indicate an error    
  } else {
    valid = true;
  }
}

// This function is called when the form is submitted
function validate(evt){
  // Invoke the validation functions in case the fields have not been checked yet
  checkTime();
  checkRoomNr();
  if(!valid){
     evt.preventDefault(); // Cancel the form's submission
     console.log("Submission cancelled due to invalid data");
  }
}
<form action="#">
  <div>
    <label for="time-until">Time</label>      
    <input type="text" id="time-until">
  </div>  
  <div>
    <label for="room">Room</label>      
    <input type="text" id="room">
  <div>
  <button id="show-schedule">Show</button>
<form>

0
投票

function checkTime( val ) {                     //Pass a value
  return /^\d{1,2}:\d{2}([ap]m)?$/.test( val ); //Return a boolean
}

function checkNum( val ) {    //Pass a value
  return /^\d+$/.test( val ); //Return a boolean
}

const time = document.getElementById("time-until"),
      room = document.getElementById("room"),
      show = document.getElementById("show-schedule");

function validateForm () {
  show.disabled = (checkTime( time.value ) && checkNum( room.value )) === false;
}

[time, room].forEach( el => el.addEventListener("input", validateForm) );
<div>
  <label for="time-until">Time</label>
  <input type="text" id="time-until">
</div>
<div>
  <label for="room">Room</label>
  <input type="text" id="room">
</div>

<!-- MAKE BUTTON DISABLED -->
<button id="show-schedule" disabled>Show</button>

现在,无论输入ID如何,您都可以重用checkTime( val )等函数。


-1
投票

这可能是一个起点基本上你需要添加事件处理程序和连接time_untiloptand time_untilopt并将disabled添加到show按钮。并倾听变化。有很多方法,这只是一个想法。

const button = document.getElementById('show-schedule');
const time_untilopt = document.getElementById('time-until');
const roomopt = document.getElementById('room');

function checkTime() {
  re = /^\d{1,2}:\d{2}([ap]m)?$/;
  if (time_untilopt.value != '' && !time_untilopt.value.match(re)) {
    alert("Wrong time!");
    return false;
  }
  return true;
}

function checkRoomNr() {
  var numbers = /^[0-9]+$/;
  if (roomopt.value.match(numbers)) {
    console.log("is number");
    return true;
  } else {
    console.log("not a number!");
    return false;
  }
}

function change() {
  button.disabled = !(checkTime() && checkRoomNr());
}
<div>
  <label for="time-until">Time</label>
  <input type="text" id="time-until" onchange="change()">
</div>
<div>
  <label for="room">Room</label>
  <input type="text" id="room" onchange="change()">
</div>
<button id="show-schedule" disabled="true">Show</button>

-2
投票

在你的两个函数中,你需要设置你的变量(time_untiloptroomopt)来实际指向你的两个<input>字段。那么你只需要return true,如果他们通过验证,和return false,如果他们没有。

要触发这些检查,您需要为提交设置onlick属性,该属性与第三个函数绑定,我将其命名为show()。第三个函数应该有条件地检查两个其他函数是否返回true。如果他们这样做,一切都很好,你可以继续提交。如果它们不好,那么在这个功能中也只需要return false

这可以在以下内容中看到:

function checkTime() {
  re = /^\d{1,2}:\d{2}([ap]m)?$/;
  var time_untilopt = document.getElementById('time-until');
  if (time_untilopt.value != '' && !time_untilopt.value.match(re)) {
    return true;
  }
  else {
    console.log("Wrong time!");
    return false;
  }
}

function checkRoomNr() {
  var numbers = /^[0-9]+$/;
  var roomopt = document.getElementById('room');
  if (roomopt.value.match(numbers)) {
    return true;
  } else {
    console.log("The room number is not a number!");
    return false;
  }
}

function show() {
  if (checkTime() && checkRoomNr()) {
    console.log('Both validations passed!');
    return true;
  }
  else {
    return false;
  }
}
<div>
  <label for="time-until">Time</label>
  <input type="text" id="time-until">
</div>
<div>
  <label for="room">Room</label>
  <input type="text" id="room">
</div>
<button id="show-schedule" onclick="show()">Show</button>

另请注意,您的checkTime()功能实际上与您想要的完全相反;如果时间不为空且与验证匹配,则需要返回true,而不是false。在上面的例子中已经纠正了这个问题。

希望这可以帮助! :)

© www.soinside.com 2019 - 2024. All rights reserved.