google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Tạo trình kiểm tra vùng nhập liệu tốt hơn với HTML Bài viết này sẽ hướng dẫn chi tiết bạn cách thức để tạo ra các trình kiểm tra dữ liệu tối ưu và hiệu quả hơn. Thông qua bài viết này, bạn có thể nắm bắt được tốt hơn cách thức dùng JavaScript để xử lí các loại dữ liệu như mật khẩu, định dạng thư điện tử hợp lệ, địa chỉ URL, dữ liệu dạng số/chữ...

Vui lòng vào trang trong để xem chi tiết, và có thể xem qua các bài viết cùng tác giả:
- Hướng dẫn kiểm tra định dạng ngày tháng hợp lệ với JavaScript


Nhãn: trình kiểm tra, vùng nhập liệu, kiểm tra dữ liệu, mật khẩu, thư điện tử, địa chỉ URL

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

4. Styling valid/invalid inputs using CSS

While the code we're using is slightly more complicated, this should get you started:

input:required:invalid, input:focus:invalid {
  /* insert your own styles for invalid form input */
  -moz-box-shadow: none;
}

The first set of styles can be used to mark an input box as 'invalid', by adding an icon, colouring the text or borders or similar. It will apply to inputs that are required but empty, or to inputs that have a required format/pattern which hasn't yet been met.

The -moz-box-shadow style is there just to prevent Firefox 4 Beta from adding it's default red border.

For inputs that are both required and 'valid' you can use the following:

input:required:valid {
  /* insert your own styles for valid form input */
}

Some of the articles below, particularly the first two, provide other style/scripting options and solutions for supporting older browsers.

5. Sample styling using images and sprites

As shown above, once you've added HTML5 attributes to your form elements, they can be easily styled using CSS so that each input field is clearly marked as valid or invalid.

input:required:invalid, input:focus:invalid {
  background-image: url(/images/invalid.png);
  background-position: right top;
  background-repeat: no-repeat;
}
input:required:valid {
  background-image: url(/images/valid.png);
  background-position: right top;
  background-repeat: no-repeat;
}

Here you can see the above styles applied to a required input field:

Your Name: (required)

This solution is still more complicated than it needs to be as it requires two extra images to be loaded. Fortunately, we can assume that all browsers supporting HTML5 form validation techniques will also support images being replaced in the CSS by 'Base64 encoded datasets'.

Using a service such as Spritebaker or other techniques, the above style settings become:

input:required:invalid, input:focus:invalid {
  background-image: 
url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAeVJREFUeNqkU01oE1EQ/mazSTdRmqSxLVSJVKU9RYoHD8WfHr16kh5EFA8eSy6hXrwUPBSKZ6E9V1CU4tGf0DZWDEQrGkhprRDbCvlpavan3ezu+LLSUnADLZnHwHvzmJlvvpkhZkY7IqFNaTuAfPhhP/8Uo87SGSaDsP27hgYM/lUpy6lHdqsAtM+BPfvqKp3ufYKwcgmWCug6oKmrrG3PoaqngWjdd/922hOBs5C/jJA6x7AiUt8VYVUAVQXXShfIqCYRMZO8/N1N+B8H1sOUwivpSUSVCJ2MAjtVwBAIdv+AQkHQqbOgc+fBvorjyQENDcch16/BtkQdAlC4E6jrYHGgGU18Io3gmhzJuwub6/fQJYNi/YBpCifhbDaAPXFvCBVxXbvfbNGFeN8DkjogWAd8DljV3KRutcEAeHMN/HXZ4p9bhncJHCyhNx52R0Kv/XNuQvYBnM+CP7xddXL5KaJw0TMAF8qjnMvegeK/SLHubhpKDKIrJDlvXoMX3y9xcSMZyBQ+tpyk5hzsa2Ns7LGdfWdbL6fZvHn92d7dgROH/730YBLtiZmEdGPkFnhX4kxmjVe2xgPfCtrRd6GHRtEh9zsL8xVe+pwSzj+OtwvletZZ/wLeKD71L+ZeHHWZ/gowABkp7AwwnEjFAAAAAElFTkSuQmCC');

  background-position: right top;
  background-repeat: no-repeat;
  -moz-box-shadow: none;
}
input:required:valid {
  background-image: 
url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAepJREFUeNrEk79PFEEUx9/uDDd7v/AAQQnEQokmJCRGwc7/QeM/YGVxsZJQYI/EhCChICYmUJigNBSGzobQaI5SaYRw6imne0d2D/bYmZ3dGd+YQKEHYiyc5GUyb3Y+77vfeWNpreFfhvXfAWAAJtbKi7dff1rWK9vPHx3mThP2Iaipk5EzTg8Qmru38H7izmkFHAF4WH1R52654PR0Oamzj2dKxYt/Bbg1OPZuY3d9aU82VGem/5LtnJscLxWzfzRxaWNqWJP0XUadIbSzu5DuvUJpzq7sfYBKsP1GJeLB+PWpt8cCXm4+2+zLXx4guKiLXWA2Nc5ChOuacMEPv20FkT+dIawyenVi5VcAbcigWzXLeNiDRCdwId0LFm5IUMBIBgrp8wOEsFlfeCGm23/zoBZWn9a4C314A1nCoM1OAVccuGyCkPs/P+pIdVIOkG9pIh6YlyqCrwhRKD3GygK9PUBImIQQxRi4b2O+JcCLg8+e8NZiLVEygwCrWpYF0jQJziYU/ho2TUuCPTn8hHcQNuZy1/94sAMOzQHDeqaij7Cd8Dt8CatGhX3iWxgtFW/m29pnUjR7TSQcRCIAVW1FSr6KAVYdi+5Pj8yunviYHq7f72po3Y9dbi7CxzDO1+duzCXH9cEPAQYAhJELY/AqBtwAAAAASUVORK5CYII=');

  background-position: right top;
  background-repeat: no-repeat;
}

The above code can now be copied directly to your CSS style sheet. There's no need to copy any images and, especially if your style-sheets are gzip-compressed, there will be next to no impact on load times. In a few minutes you could have your whole website updated.

For the browser-impaired, this is how the input field appears in Safari with either the image or the 'sprite' backgrounds (there is no difference between the two options):

HTML5 required example 2

The same styling can be extended to textarea elements, but won't work for checkboxes, select elements, etc. For the latter you might want to place the valid/invalid markers alongside the element or format those input elements using borders, background colours, etc.

6. Fallback for the placeholder attribute

The following JavaScript, placed or included at the end of the page, should enable support for the placeholder attribute in INPUT fields at least for Internet Explorer 8+, Firefox and Opera:

// ref: http://diveintohtml5.org/detect.html
function supports_input_placeholder()
{
  var i = document.createElement('input');
  return 'placeholder' in i;
}

if(!supports_input_placeholder()) {
  var fields = document.getElementsByTagName('INPUT');
  for(var i=0; i < fields.length; i++) {
    if(fields[i].hasAttribute('placeholder')) {
      fields[i].defaultValue = fields[i].getAttribute('placeholder');
      fields[i].onfocus = function() { if(this.value == this.defaultValue) this.value = ''; }
      fields[i].onblur = function() { if(this.value == '') this.value = this.defaultValue; }
    }
  }
}

7. INPUT patterns for different data types

URL input pattern:

input type="url" pattern="https?://.+"

IP Address input pattern:

input type="text" pattern="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"

Date input pattern:

input type="text" pattern="\d{1,2}/\d{1,2}/\d{4}"

Price input pattern:

input type="text" pattern="\d+(\.\d{2})?"

Latitude/Longitude input pattern:

input type="text" pattern="-?\d{1,3}\.\d+"

Feel free to send any patterns you find useful using the Feedback form.

8. References

Related Articles

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web