Popular Posts
Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement... Expression in polymer Since Polymer doesn't support expression directly, I create an express function as expression alternative. Demo Demo source <htm... Get files name in batch Windows Batch : get filename using [%%~ni] Linux Shell Script : get filename using [awk, sed] windows sample : rename all *.htm file to ...
Stats
Showing posts with label jQuery. Show all posts
Showing posts with label jQuery. Show all posts
jQuery.validationEngine
The following attribute's value will be loaded for the relative validation rule:
data-errormessage-value-missing
  • required
  • groupRequired
  • condRequired
data-errormessage-type-mismatch
  • past
  • future
  • dateRange
  • dateTimeRange
data-errormessage-pattern-mismatch
  • creditCard
  • equals
data-errormessage-range-underflow
  • minSize
  • min
  • minCheckbox
data-errormessage-range-overflow
  • maxSize
  • max
  • maxCheckbox
data-errormessage-custom-error
  • custom
  • ajax
  • funcCall
data-errormessage
  • a generic fall-back error message

Validators
  • required : Speaks for itself, fails if the element has no value. This validator can apply to pretty much any kind of input field.
  • groupRequired : At least one of the field of the group must be filled. It needs to be given a group name that is unique across the form.
  • condRequired : This makes the field required, but only if any of the referred fields has a value.
  • custom[regex_name] : Validates the element's value to a predefined list of regular expressions.
  • custom[function_name] : Validates the element's value to a predefined function included in the language file (compared to funcCall that can be anywhere in your application),
  • funcCall[methodName] : Validates a field using a third party function call. If a validation error occurs, the function must return an error message that will automatically show in the error prompt.
  • ajax[selector] : Delegates the validation to a server URL using an asynchronous Ajax request. The selector is used to identify a block of properties in the translation file, take the following for example.
  • equals[field.id] : Checks if the current field's value equals the value of the specified field.
  • min[float] : Validates when the field's value is less than, or equal to, the given parameter.
  • max[float] : Validates when the field's value is more than, or equal to, the given parameter.
  • minSize[integer] : Validates if the element content size (in characters) is more than, or equal to, the given integer. integer <= input.value.length
  • maxSize[integer] : Validates if the element content size (in characters) is less than, or equal to, the given integer. input.value.length <= integer
  • past[NOW, a date or another element's name] : Checks if the element's value (which is implicitly a date) is earlier than the given date. When "NOW" is used as a parameter, the date will be calculate in the browser. When a "#field name" is used ( The '#' is optional ), it will compare the element's value with another element's value within the same form. Note that this may be different from the server date. Dates use the ISO format YYYY-MM-DD
  • future[NOW, a date or another element's name] : Checks if the element's value (which is implicitly a date) is greater than the given date. When "NOW" is used as a parameter, the date will be calculate in the browser. When a "#field name" is used ( The '#' is optional ), it will compare the element's value with another element's value within the same form. Note that this may be different from the server date. Dates use the ISO format YYYY-MM-DD
  • minCheckbox[integer] : Validates when a minimum of integer checkboxes are selected. The validator uses a special naming convention to identify the checkboxes as part of a group.
  • maxCheckbox[integer] : Same as above but limits the maximum number of selected check boxes.
  • creditCard : Validates that a credit card number is at least theoretically valid, according the to the Luhn checksum algorithm, but not whether the specific card number is active with a bank, etc.

Custom Regex
  • phone
  • url
  • email
  • date
  • number
  • integer
  • ipv4
  • onlyNumberSp
  • onlyLetterSp
  • onlyLetterNumber
Custom prompt position
  • data-prompt-position : topLeft, topRight, centerRight, bottomLeft, bottomRight, inline
Ignore validate
jQuery delegate
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
    $(function(){
        // add row button
        $('.append_button').click(function(){
            var row = $('<div class="lister">'+new Date()+'&nbsp;&nbsp;&nbsp;<input type="button" class="row_button" value="click me!" /></div>');
            row.appendTo('.container');
        });
        
        // delegate for append button
        $('.container').delegate('.lister input:button', 'click', function(){
            alert('delegate ok!');
        });
        // delegate for append button (falied, because .lister was not found on delegate action)
        $('.container .lister').delegate('input:button', 'click', function(){
            alert('delegate, again!');
        });
    });
</script>
</head>
<body>
<div class="container">
    <input type="button" class="append_button" value="Add" />
</div>
</body>
</html>
jQuery validator: focus invalid field when calling valid()
/*
 * 在validate呼叫valid()驗證方法式, 加上focusInValid的動件
 */
(function($) {
    $.extend($.fn, {
        valid2 : function() {
            var valid = true;
            var validator;
            if ($(this[0]).is('form')) {
                validator = this.validate();
                valid = this.validate().form();
            } else {
                validator = $(this[0].form).validate();
                this.each(function() {
                    valid &= validator.element(this);
                });
            }
            if (!valid)
                validator.focusInvalid();
            return valid;
        }
    });

    // 新增一個 regex 的驗證方式
    $.validator.methods.regex = function(value, element, param) {
        return this.optional(element) || ((typeof(param) == 'function' && typeof(param.test) == 'function') ? param.test(value) : new RegExp(param).test(value));
    };
    $.validator.messages.regex = 'Please enter a valid value.';
})(jQuery);
jQuery : post/get using data() as param object
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Recursive call when post request</title>
<script type="text/javascript" src="jquery-1.5.1.js"></script>
<script type="text/javascript">
    $(function() {
        var count = 0;
        $('input:button').click(function() {
            // identity
            count++;
            var tick = count;
            // post url
            var url = '${contextPath}/';
            // post param
            var param = $(this).data();
            console.log(param);
            $('<div>(' + tick + ') Post to : ' + url + '</div>').appendTo(document.body);
            $.post(url, param, function(data) {
                $('<div style="color:blue;">(' + tick + ') Ajax works successfully.</div>').appendTo(document.body);
            });
        });
    });
</script>
</head>
<body>
<input type="button" value="click to post" data-action="test" data-name="bruce" data-age="31" />
</body>
</html>
ボタンをクリックすると、data()のオブジェクトがハンドルを値を持っているため、postするときにハンドルは再び執行することになる。つまり、クリック事件は繰り返しする。この現象を避けるには、ハンドル/イベントを削除しなければならない。
jQuery validte : regex rule
$.validator.addMethod(
    "regex",
    function(value, element, regexp) {
        var check = false;
        var re = new RegExp(regexp);
        return this.optional(element) || re.test(value);
    },
    "Please check your input."
);
$("textbox").rules("add", { regex: "^[a-zA-Z'.\s]{1,40}$" })
Change form attributes with JQuery
action = '/controller/action/id/';
target = 'upload_iframe';
enctype = 'multipart/form-data';    

$('#form1').attr("action",action);
$('#form1').attr("target",target);
$('#form1').attr("enctype",enctype);
In other browsers it works fine, but not in IE(6,7,8).
jQuery serialize form to json
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
jQuery metadata
$(document).ready(function(){
    var data = $("#message").metadata();
    var i; 
    for(i in data){
        $("#message").append("<div>"+i+"="+data[i]+"</div>");
    }
});
<div id="message" class="mess {firstName:'Bruce',lastName:'Tsai'}"></div>
jQuery validate
利用 css (class屬性), 只能處理預設驗證規則(required, email....)
*Account :
*e-mail :
利用 rules 加入驗證規則與自訂錯誤訊息
Cell Phone :
驗證成功與失敗時的處置
Age1 :
Age2 :
新增移除規則
Test email1:
Test email2:
搭配 Matadata 在 class 屬性中設定驗證規則
Number1 :
自訂驗證規則
Number2 :
Social ID :
驗證規則依存性
address :
(function(){
    $("#form01").validate({
        debug: true  // 除錯模式
    });
    
    $("#form02").validate({
        rules: {
            cellphone: {  // form.name
                required: true,
                digits: true,
                minlength: 5
            }
        },
        messages: {
            cellphone: {  // form.name
                required: "請填寫電話!",
                digits: "請填寫電話號碼!",
                minlength: $.format("至少填入 {0} 個數值")  // 對應驗證的參數
            }
        },
        debug: true
    });
    
    $("#form03").validate({
        submitHandler: function(form){
            alert("Age1 value : " + $("#age1").val());
            form.submit();
            //$(form).ajaxSubmit();
        },
        invalidHandler: function(form, validator){
            var errors = validator.numberOfInvalids();
            alert($.format("錯誤數 : {0}", errors));
        }
    });
    
    $("#form04").validate();
    $("#testemail1").rules("add", {required:true});
    
    $("#form05").validate();
    
    // 新增驗證規則, 作法一
    $.validator.methods.lessThanSquare = function(value, element, param){
        // @value 輸入的值
        // @element 驗證的目標元件
        // @param 設定規則時的參數
        return value * value < param;
    };
    // 新增驗證規則, 作法二
    $.validator.addMethod("testSocialId", function(value, element, param){
        return /\w\d{9}/.test(value);
    }, "身份證號驗證錯誤");
    $("#form06").validate({
        rules: {
            number2: {
                required: true,
                digits: true,
                lessThanSquare: 100
            },
            socialid: {
                required: true,
                testSocialId: true
            }
        },
        messages: {
            number2: {
                lessThanSquare: "數值錯誤"
            }
        }
    });
    
    $("#form07").validate({
        rules: {
            address: {
                required: "#requiredaddresscheck:checked"
            }
        }
    });
})();
CKEditor compact implement guid
implement way 1 : use css
<textarea id="editor" class="ckeditor"></textarea>
implement way 2 : use javascript
<textarea id="editor"></textarea>
<script type="text/javascript">
// default
CKEDITOR.replace("editor");
// with settings
CKEDITOR.replace("editor", {skin:"office2003", toolbar:"Basic"});
</script>
implement way 3 : use jQuery
<textarea id="editor"></textarea>
<script type="text/javascript">
// default
$("#editor").ckeditor();
// with settings
$("#editor").ckeditor(
    function(){
        // callback code
    },
    {
        uiColor: "pink",
        skin: "kama",
        toolbar: [
            ["Source", "Preview"],
            "/",  // line break
            ["Cut", "Copy", "Paste", "PasteText", "PasteFromWord", "Print", "SpellChecker", "Scayt"]
        ]
    }
);
</script>
toolbar properties
"Source"
"Save" "NewPage" "Preview" "Templates"
"Cut" "Copy" "Paste" "PasteText" "PasteFromWord" "Print" "SpellChecker" "Scayt"
"Undo" "Redo" "Find" "Replace" "SelectAll" "RemoveFormat"
"Form" "Checkbox" "Radio" "TextField" "Textarea" "Select" "Button" "ImageButton" "HiddenField"
"Bold" "Italic" "Underline" "Strike" "Subscript" "Superscript"
"NumberedList" "BulletedList" "Outdent" "Indent" "Blockquote"
"JustifyLeft" "JustifyCenter" "JustifyRight" "JustifyBlock"
"Link" "Unlink" "Anchor"
"Image" "Flash" "Table" "HorizontalRule" "Smiley" "SpecialChar" "PageBreak"
"Styles" "Format" "Font" "FontSize"
"TextColor" "BGColor"
"Maximize" "ShowBlocks" "About"

CKEditor 3 JavaScript API Documentation