google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Hướng dẫn kiểm tra dữ liệu tốt hơn với JavaScript Bài viết này tập trung chủ yếu vào việc hướng dẫn bạn dùng các mã thuần JavaScript (plain) để kiểm tra dữ liệu của các loại trường nhập liêu với ngôn ngữ JavaScript. Bài viết sẽ hướng dẫn bạn cách thức để xử lý các dữ liệu dạng số, dạng chuỗi; xử lí dữ liệu của các khung nhập liệu, dấu kiểm, dấu chọn và các kiểu kết hợp. Vui lòng vào trang chi tiết để xem hướng dẫn đầy đủ cùng với mã nguồn JavaScript ví dụ mẫu đính kèm.

Các bài viết khác cùng tác giả:
- Kiểm tra số thẻ tín dụng với JavaScript
- Tạo trình kiểm tra vùng nhập liệu tốt hơn với HTML
- Hướng dẫn kiểm tra định dạng ngày tháng hợp lệ với JavaScript


Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

For an alternative approach to client-side form validation, without JavaScript, check out our new article on HTML5 Form Validation which is available now in most modern browsers.

Note: When the form input is important, it must always be checked or re-checked by using a server-side script. Otherwise a browser with JavaScript disabled, or a hacker trying to compromise your site, can easily submit invalid data.

Restricting input to alphanumeric characters

In the following example, the single input box, named input, must: a) not be empty; and b) contain only alphanumeric characters and spaces. Only if both tests are passed can the form be submitted.

<script type="text/javascript">
   
  function checkForm(form)
  {
    // validation fails if the input is blank
    if(form.inputfield.value == '') {
      alert("Error: Input is empty!");
      form.inputfield.focus();

      return false;
    }

    // regular expression to match only alphanumeric characters and spaces
    var re = /^[\w ]+$/;
    
    // validation fails if the input doesn't match our regular expression
    if(!re.test(form.inputfield.value)) {
      alert("Error: Input contains invalid characters!");
      form.inputfield.focus();
      return false;
    }
    
    // validation was successful
    return true;

  }
  
</script>

Note: The pre-defined class \w represents any alphanumeric character as well as the '_' character.

The regular expression ^[\w ]+$ will fail if the input is empty as it requires at least one character (because we used + instead of *). The first test in the example is therefore only necessary in order to provide a different error message when the input is blank.

The purpose of a form validation script is to return a boolean value (true or false) to the onSubmit event handler. A value of true means that form will be submitted while a false value will block the form from being submitting. The focus() command is used to set the focus to the problem element.

You can test the above script with different input values using this form:

Input:

The form is put together as follows:

<form method="POST" action="action" onSubmit="return checkForm(this);">
Input: <input type="text" size="32" name="input"> <input type="submit">

</form>

The name attribute of the input field is used to reference that field from within the checkForm function. With the advent of DHTML it's tempting to use id's to reference form fields, but that can lead to namespace conflicts and why make things more complicated than necessary.

When the form is submitted - either by hitting Enter or clicking on the Submit button - the onSubmit handler is triggered. This then calls our checkForm() function, passing a reference to itself (the form) as the only variable. This makes the value of the input box available within the function as form.input.value (the 'value' of the field called 'input' belonging to the form). Other form values are available using a similar syntax, although this becomes more complicated if you're using SELECT lists, checkboxes or radio buttons (see below for examples).

The checkForm function tests the form input against our conditions, returning a value of true if the form is to be submitted (when all tests have been passed) or false to abort (cancel) the form submission. It's that simple.

In a real-life situation you will most likely have more fields to check, and more complicated conditions, but the principle remains the same. All you need to do is extend the checkForm function to encompass the new fields and conditions:

  function checkForm(form)
  {
    if(!condition1) {
       alert("Error: error message");
       form.fieldname.focus();
       return false;
    }
    if(!condition2) {
       alert("Error: error message");
       form.fieldname.focus();
       return false;
    }
    ...
    return true;
  }

When a return command is encountered, execution of the function is halted. In other words if the first condition fails, the second condition will not be tested and so forth. Only when all conditions have been satisfied do we reach the return true command, in which case the form will be submitted.

You'll see that the all validation scripts presented on this and subsequent pages adhere to the same basic format.

Working with different types of FORM elements

Text/Textarea/Password boxes

The value of a text input box (or a textarea or password input) is available using the syntax form.fieldname.value. This is not the case for other input types.

form.fieldname.value

To check whether two inputs have the same is quite simple:

if(form.field1.value == form.field2.value) {
  // values are identical
}

Note: Make sure to always use == for comparisons. If you use = (the assignment operator) instead then it can take a long time to debug.

and to see if they have different values we just reverse the logic:

if(form.field1.value != form.field2.value) {
  // values are different
}

If you want to test numeric values (or add or subtract them) then you first have to convert them from strings to numbers. By default all form values are available as strings only.

  var field1 = parseInt(form.field1.value);
  var field2 = parseInt(form.field2.value);
  if(field1 > field2) {
    // field1 as a number is greater than field2 as a number
  }

Note: parseFloat is the same as parseInt except that it works for floating point numbers as well as integers.

Select/Combo/Drop-down boxes

The value of a SELECT input element is accessed using:

var selectBox = form.fieldname;
selectBox.options[selectBox.selectedIndex].value
selectBox.options[selectBox.selectedIndex].text

where fieldname is the SELECT element, which has an array of options and a value selectedIndex that tells you which option has been selected. The illustration below shows this relationship:

Note that the 'I' in selectedIndex needs to be capitalised - JavaScript functions and variables are always case-sensitive.

If you define a value for the OPTION elements in your SELECT list, then .value will return that, while .text will return the text that is visible in the browser. Here's an example of what this refers to:

  <option value="value">text</option>

Note: One of the most common problems for novices is that Internet Explorer allows you to access the value of the selected option using the same format as for text boxes above. This is wrong!

If you just want to check that an option has been chosen (ie. that the SELECT box is no longer in it's default state) then you can use:

  if(form.fieldname.selectedIndex > 0) {
    // an option has been selected
  } else {
    // no option selected
  }

Checkboxes

These really are simple:

form.checkboxfield.checked

will return a boolean value (true or false) indicating whether the checkbox is in a 'checked' state.

  function checkForm(form)
  {
    if(form.checkboxfield.checked) {
      alert("The checkbox IS checked");
    } else {
      alert("The checkbox IS NOT checked");
    }
    return false;
  }

Note: You don't need to test using form.checkboxfield.checked == true as the value is already boolean.

Check me!

Radio buttons

Radio buttons are implemented as if they were an array of checkboxes. To find out which value (if any) has been selected, you need to loop through the array until you find which one has been selected:

  function checkRadio(field)
  {
    for(var i=0; i < field.length; i++) {
      if(field[i].checked) return field[i].value;
    }
    return false;
  }

The form handler function is then the following:

  function checkForm(form) 
  {
    if(radioValue = checkRadio(form.radiofield)) {
      alert("You selected " + radioValue);
      return true;
    } else {
      alert("Error: No value was selected!");
      return false;
    }
  }
Red Green Blue

Checkbox arrays

If you're working with arrays of checkboxes to submit data to a server-side script then you might already have some grey hairs from trying to figure out how to validate the input using JavaScript.

The problem is that, to have the data submitted in a 'nice' format to the server, the name attributes of all the checkboxes in the array are often set to the same value: a name ending with []. This makes it difficult to address them directly using JavaScript.

In this example, the checkboxes are defined as:

<input type="checkbox" name="pref[]" value="value"> label
Example: checkbox array

Which of the following pastimes do you enjoy?

Art /Antiques
Camping/Hiking
Cooking
Computer games
Dining Out
Fishing
Gardening
Going to Pubs/Clubs
Internet/Computers
Music
Photography
Reading
Television/Videos
Theatre/Cinema
Sports/Fitness

When you submit the form you will be notified through an alert message how many items you checked, and what they were. This is calculated using a new function:

  // Original JavaScript code by Chirp Internet: www.chirp.com.au
  // Please acknowledge use of this code by including this header.

  function checkArray(form, arrayName)
  {
    var retval = new Array();
    for(var i=0; i < form.elements.length; i++) {
      var el = form.elements[i];
      if(el.type == "checkbox" && el.name == arrayName && el.checked) {
        retval.push(el.value);
      }
    }
    return retval;
  }

The form handler that calls this function and displays the alerts is as follows:

  function checkForm(form)
  {
    var itemsChecked = checkArray(form, "pref[]");
    alert("You selected " + itemsChecked.length + " items");
    if(itemsChecked.length > 0) {
      alert("The items selected were:\n\t" + itemsChecked);
    }
    return false;
  }

The checkArray function returns an array contains all the select values.

Normally you would modify this so that you could submit or not submit the form based on the number of items selected. For example "at least two" or "no more than five". This should be a simple exercise.

Combining Form Elements in Conditions

In more complicated forms you will want to set conditions on the form that combine multiple elements. For example, a text input that only needs to have a value if a checkbox is checked:

function checkForm(form)
{
...

  if(form.checkboxname.checked && (form.textinputname.value == '')) {
    alert('Error: error message');
    form.textinputname.focus();
    return false;
  }

...
}

or conditions that vary according to a radio button selection:

function checkForm(form)
{
...

  var radioValue = checkRadio(radiofield);
  switch(radioValue)
  {
    case 'Red':
      conditions to apply if 'Red' is selected
      break;

    case 'Blue':
      conditions to apply if 'Blue' is selected
      break;

    default:
      conditions to apply in all other cases
  }

...
}

Using simple logical operators and the functions supplied above you can do all sorts of client-side form validation. To take things a step further you can even explore Ajax Form Validation which lets you supply real-time feedback using server-side scripts triggered by JavaScript events.

Related Articles

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web