GVKun编程网logo

magento 表单验证 Prototype Javascript Validation(from表单验证)

19

在本文中,我们将为您详细介绍magento表单验证PrototypeJavascriptValidation的相关知识,并且为您解答关于from表单验证的疑问,此外,我们还会提供一些关于javascr

在本文中,我们将为您详细介绍magento 表单验证 Prototype Javascript Validation的相关知识,并且为您解答关于from表单验证的疑问,此外,我们还会提供一些关于javascript - 关于Array.prototype.slice.call和Array.prototype.concat.call的问题、JavaScript .prototype 如何工作? - How does JavaScript .prototype work?、javascript Array.prototype.slice使用说明_javascript技巧、Javascript Function.prototype.bind详细分析的有用信息。

本文目录一览:

magento 表单验证 Prototype Javascript Validation(from表单验证)

magento 表单验证 Prototype Javascript Validation(from表单验证)

While Javascript form validation shouldn''t be your only form of defense with regards to user input, it definitely improves the usability and efficiency of a site. It can also give your site a web 2.0 feel - which users seem to love.

Javascript Validation in Magento

By default Magento uses a file called form.js (js/varien/form.js) to provide abstract Javascript functions for forms. The most useful application of this class - in my opinion - is the form validation. To achieve this validation, form.js uses the Validation class which is part of the Prototype Javascript library. It works by checking form inputs for certain class names. Each class name tells the validator to perform certain checks on the value inside the input.

Custom Form Validation

Adding Javascript validation to your own forms is extremely simple. First, you need to create a Form (form.js) object to represent your form.

<script type="text/javascript">
//< ![CDATA[
  var myForm= new VarienForm(''formId'', true);
//]]>
</script>

The first parameter, in this case formId, is the ID of your form. The second parameter defines whether or not the first input field in the form should steal the cursor focus. If set to true, the cursor will automatically be moved into the first input field and any user input will be entered into this field. You can disable this functionality by setting the second parameter to false.

Now that you have created a Javascript object to represent your form you need to add some validation rules to your form inputs.

<label for="name">Name *</label>
<input type="text" id="name" name="name" value=""/>
<label for="email">Email Address *</label>
<input type="text" id="email" name="email" value=""/>

Notice the classes ''required-entry'' and ''validate-email''? These both tell the classes to apply certain validation rules on the input fields. If any of the validation checks fail, the form will not be submitted and the user will be alerted to the errors.

Magento Javascript Validation Classes

For example, if you open the app/design/frontend/base/default/template/customer/form/register.phtml file and focus on the input fields and their “class” attributes you will see some of them named: “required-entry”, “validate-email”, “validate-zip-international”, etc. All of these are tied to the Java Script validation rules defined under js/prototype/validation.js file.

Validation.add(''IsEmpty'', '''', function(v) {
    return  (v == '''' || (v == null) || (v.length == 0) || /^\s+$/.test(v)); // || /^\s+$/.test(v));
});
 
Validation.addAllThese([
    [''validate-select'', ''Please select an option.'', function(v) {
                return ((v != "none") && (v != null) && (v.length != 0));
            }],
    [''required-entry'', ''This is a required field.'', function(v) {
                return !Validation.get(''IsEmpty'').test(v);
            }],
    [''validate-number'', ''Please enter a valid number in this field.'', function(v) {
                return Validation.get(''IsEmpty'').test(v) || (!isNaN(parseNumber(v)) && !/^\s+$/.test(parseNumber(v)));
            }],
    [''validate-digits'', ''Please use numbers only in this field. Please avoid spaces or other characters such as dots or commas.'', function(v) {
                return Validation.get(''IsEmpty'').test(v) ||  !/[^\d]/.test(v);
            }],
    [''validate-digits-range'', ''The value is not within the specified range.'', function(v, elm) {
                var result = Validation.get(''IsEmpty'').test(v) ||  !/[^\d]/.test(v);
                var reRange = new RegExp(/^digits-range-[0-9]+-[0-9]+$/);
                $w(elm.className).each(function(name, index) {
                    if (name.match(reRange) && result) {
                        var min = parseInt(name.split(''-'')[2], 10);
                        var max = parseInt(name.split(''-'')[3], 10);
                        var val = parseInt(v, 10);
                        result = (v >= min) && (v <= max);
                    }
                });
                return result;
            }],
    [''validate-alpha'', ''Please use letters only (a-z or A-Z) in this field.'', function (v) {
                return Validation.get(''IsEmpty'').test(v) ||  /^[a-zA-Z]+$/.test(v)
            }],
    [''validate-code'', ''Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.'', function (v) {
                return Validation.get(''IsEmpty'').test(v) ||  /^[a-z]+[a-z0-9_]+$/.test(v)
            }],
    [''validate-alphanum'', ''Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed.'', function(v) {
                return Validation.get(''IsEmpty'').test(v) ||  /^[a-zA-Z0-9]+$/.test(v) /*!/\W/.test(v)*/
            }],
    [''validate-street'', ''Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field.'', function(v) {
                return Validation.get(''IsEmpty'').test(v) ||  /^[ \w]{3,}([A-Za-z]\.)?([ \w]*\#\d+)?(\r\n| )[ \w]{3,}/.test(v)
            }],
    [''validate-phoneStrict'', ''Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.'', function(v) {
                return Validation.get(''IsEmpty'').test(v) || /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/.test(v);
            }],
    [''validate-phoneLax'', ''Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890.'', function(v) {
                return Validation.get(''IsEmpty'').test(v) || /^((\d[-. ]?)?((\(\d{3}\))|\d{3}))?[-. ]?\d{3}[-. ]?\d{4}$/.test(v);
            }],
    [''validate-fax'', ''Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890.'', function(v) {
                return Validation.get(''IsEmpty'').test(v) || /^(\()?\d{3}(\))?(-|\s)?\d{3}(-|\s)\d{4}$/.test(v);
            }],
    [''validate-date'', ''Please enter a valid date.'', function(v) {
                var test = new Date(v);
                return Validation.get(''IsEmpty'').test(v) || !isNaN(test);
            }],
    [''validate-email'', ''Please enter a valid email address. For example johndoe@domain.com.'', function (v) {
                //return Validation.get(''IsEmpty'').test(v) || /\w{1,}[@][\w\-]{1,}([.]([\w\-]{1,})){1,3}$/.test(v)
                //return Validation.get(''IsEmpty'').test(v) || /^[\!\#$%\*/?|\^\{\}`~&\''\+\-=_a-z0-9][\!\#$%\*/?|\^\{\}`~&\''\+\-=_a-z0-9\.]{1,30}[\!\#$%\*/?|\^\{\}`~&\''\+\-=_a-z0-9]@([a-z0-9_-]{1,30}\.){1,5}[a-z]{2,4}$/i.test(v)
                return Validation.get(''IsEmpty'').test(v) || /^([a-z0-9,!\#\$%&''\*\+\/=\?\^_`\{\|\}~-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z0-9,!\#\$%&''\*\+\/=\?\^_`\{\|\}~-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*@([a-z0-9-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z0-9-]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*\.(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]){2,})$/i.test(v)
            }],
    [''validate-emailSender'', ''Please use only visible characters and spaces.'', function (v) {
                return Validation.get(''IsEmpty'').test(v) ||  /^[\S ]+$/.test(v)
                    }],
    [''validate-password'', ''Please enter 6 or more characters. Leading or trailing spaces will be ignored.'', function(v) {
                var pass=v.strip(); /*strip leading and trailing spaces*/
                return !(pass.length>0 && pass.length < 6);
            }],
    [''validate-admin-password'', ''Please enter 7 or more characters. Password should contain both numeric and alphabetic characters.'', function(v) {
                var pass=v.strip();
                if (0 == pass.length) {
                    return true;
                }
                if (!(/[a-z]/i.test(v)) || !(/[0-9]/.test(v))) {
                    return false;
                }
                return !(pass.length < 7);
            }],
    [''validate-cpassword'', ''Please make sure your passwords match.'', function(v) {
                var conf = $(''confirmation'') ? $(''confirmation'') : $$(''.validate-cpassword'')[0];
                var pass = false;
                if ($(''password'')) {
                    pass = $(''password'');
                }
                var passwordElements = $$(''.validate-password'');
                for (var i = 0; i < passwordElements.size(); i++) {
                    var passwordElement = passwordElements[i];
                    if (passwordElement.up(''form'').id == conf.up(''form'').id) {
                        pass = passwordElement;
                    }
                }
                if ($$(''.validate-admin-password'').size()) {
                    pass = $$(''.validate-admin-password'')[0];
                }
                return (pass.value == conf.value);
            }],
    [''validate-url'', ''Please enter a valid URL. Protocol is required (http://, https:// or ftp://)'', function (v) {
                v = (v || '''').replace(/^\s+/, '''').replace(/\s+$/, '''');
                return Validation.get(''IsEmpty'').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))(\.[A-Z0-9]([A-Z0-9_-]*[A-Z0-9]|))*)(:(\d+))?(\/[A-Z0-9~](([A-Z0-9_~-]|\.)*[A-Z0-9~]|))*\/?$/i.test(v)
            }],
    [''validate-clean-url'', ''Please enter a valid URL. For example http://www.example.com or www.example.com'', function (v) {
                return Validation.get(''IsEmpty'').test(v) || /^(http|https|ftp):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i.test(v) || /^(www)((\.[A-Z0-9][A-Z0-9_-]*)+.(com|org|net|dk|at|us|tv|info|uk|co.uk|biz|se)$)(:(\d+))?\/?/i.test(v)
            }],
    [''validate-identifier'', ''Please enter a valid URL Key. For example "example-page", "example-page.html" or "anotherlevel/example-page".'', function (v) {
                return Validation.get(''IsEmpty'').test(v) || /^[a-z0-9][a-z0-9_\/-]+(\.[a-z0-9_-]+)?$/.test(v)
            }],
    [''validate-xml-identifier'', ''Please enter a valid XML-identifier. For example something_1, block5, id-4.'', function (v) {
                return Validation.get(''IsEmpty'').test(v) || /^[A-Z][A-Z0-9_\/-]*$/i.test(v)
            }],
    [''validate-ssn'', ''Please enter a valid social security number. For example 123-45-6789.'', function(v) {
            return Validation.get(''IsEmpty'').test(v) || /^\d{3}-?\d{2}-?\d{4}$/.test(v);
            }],
    [''validate-zip'', ''Please enter a valid zip code. For example 90602 or 90602-1234.'', function(v) {
            return Validation.get(''IsEmpty'').test(v) || /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(v);
            }],
    [''validate-zip-international'', ''Please enter a valid zip code.'', function(v) {
            //return Validation.get(''IsEmpty'').test(v) || /(^[A-z0-9]{2,10}([\s]{0,1}|[\-]{0,1})[A-z0-9]{2,10}$)/.test(v);
            return true;
            }],
    [''validate-date-au'', ''Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006.'', function(v) {
                if(Validation.get(''IsEmpty'').test(v)) return true;
                var regex = /^(\d{2})\/(\d{2})\/(\d{4})$/;
                if(!regex.test(v)) return false;
                var d = new Date(v.replace(regex, ''$2/$1/$3''));
                return ( parseInt(RegExp.$2, 10) == (1+d.getMonth()) ) &&
                            (parseInt(RegExp.$1, 10) == d.getDate()) &&
                            (parseInt(RegExp.$3, 10) == d.getFullYear() );
            }],
    [''validate-currency-dollar'', ''Please enter a valid $ amount. For example $100.00.'', function(v) {
                // [$]1[##][,###]+[.##]
                // [$]1###+[.##]
                // [$]0.##
                // [$].##
                return Validation.get(''IsEmpty'').test(v) ||  /^\$?\-?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}\d*(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$/.test(v)
            }],
    [''validate-one-required'', ''Please select one of the above options.'', function (v,elm) {
                var p = elm.parentNode;
                var options = p.getElementsByTagName(''INPUT'');
                return $A(options).any(function(elm) {
                    return $F(elm);
                });
            }],
    [''validate-one-required-by-name'', ''Please select one of the options.'', function (v,elm) {
                var inputs = $$(''input[name="'' + elm.name.replace(/([\\"])/g, ''\\$1'') + ''"]'');
 
                var error = 1;
                for(var i=0;i<inputs.length;i++) {
                    if((inputs[i].type == ''checkbox'' || inputs[i].type == ''radio'') && inputs[i].checked == true) {
                        error = 0;
                    }
 
                    if(Validation.isOnChange && (inputs[i].type == ''checkbox'' || inputs[i].type == ''radio'')) {
                        Validation.reset(inputs[i]);
                    }
                }
 
                if( error == 0 ) {
                    return true;
                } else {
                    return false;
                }
            }],
    [''validate-not-negative-number'', ''Please enter a valid number in this field.'', function(v) {
                v = parseNumber(v);
                return (!isNaN(v) && v>=0);
            }],
    [''validate-state'', ''Please select State/Province.'', function(v) {
                return (v!=0 || v == '''');
            }],
 
    [''validate-new-password'', ''Please enter 6 or more characters. Leading or trailing spaces will be ignored.'', function(v) {
                if (!Validation.get(''validate-password'').test(v)) return false;
                if (Validation.get(''IsEmpty'').test(v) && v != '''') return false;
                return true;
            }],
    [''validate-greater-than-zero'', ''Please enter a number greater than 0 in this field.'', function(v) {
                if(v.length)
                    return parseFloat(v) > 0;
                else
                    return true;
            }],
    [''validate-zero-or-greater'', ''Please enter a number 0 or greater in this field.'', function(v) {
                if(v.length)
                    return parseFloat(v) >= 0;
                else
                    return true;
            }],
    [''validate-cc-number'', ''Please enter a valid credit card number.'', function(v, elm) {
                // remove non-numerics
                var ccTypeContainer = $(elm.id.substr(0,elm.id.indexOf(''_cc_number'')) + ''_cc_type'');
                if (ccTypeContainer && typeof Validation.creditCartTypes.get(ccTypeContainer.value) != ''undefined''
                        && Validation.creditCartTypes.get(ccTypeContainer.value)[2] == false) {
                    if (!Validation.get(''IsEmpty'').test(v) && Validation.get(''validate-digits'').test(v)) {
                        return true;
                    } else {
                        return false;
                    }
                }
                return validateCreditCard(v);
            }],
    [''validate-cc-type'', ''Credit card number does not match credit card type.'', function(v, elm) {
                // remove credit card number delimiters such as "-" and space
                elm.value = removeDelimiters(elm.value);
                v         = removeDelimiters(v);
 
                var ccTypeContainer = $(elm.id.substr(0,elm.id.indexOf(''_cc_number'')) + ''_cc_type'');
                if (!ccTypeContainer) {
                    return true;
                }
                var ccType = ccTypeContainer.value;
 
                if (typeof Validation.creditCartTypes.get(ccType) == ''undefined'') {
                    return false;
                }
 
                // Other card type or switch or solo card
                if (Validation.creditCartTypes.get(ccType)[0]==false) {
                    return true;
                }
 
                // Matched credit card type
                var ccMatchedType = '''';
 
                Validation.creditCartTypes.each(function (pair) {
                    if (pair.value[0] && v.match(pair.value[0])) {
                        ccMatchedType = pair.key;
                        throw $break;
                    }
                });
 
                if(ccMatchedType != ccType) {
                    return false;
                }
 
                if (ccTypeContainer.hasClassName(''validation-failed'') && Validation.isOnChange) {
                    Validation.validate(ccTypeContainer);
                }
 
                return true;
            }],
     [''validate-cc-type-select'', ''Card type does not match credit card number.'', function(v, elm) {
                var ccNumberContainer = $(elm.id.substr(0,elm.id.indexOf(''_cc_type'')) + ''_cc_number'');
                if (Validation.isOnChange && Validation.get(''IsEmpty'').test(ccNumberContainer.value)) {
                    return true;
                }
                if (Validation.get(''validate-cc-type'').test(ccNumberContainer.value, ccNumberContainer)) {
                    Validation.validate(ccNumberContainer);
                }
                return Validation.get(''validate-cc-type'').test(ccNumberContainer.value, ccNumberContainer);
            }],
     [''validate-cc-exp'', ''Incorrect credit card expiration date.'', function(v, elm) {
                var ccExpMonth   = v;
                var ccExpYear    = $(elm.id.substr(0,elm.id.indexOf(''_expiration'')) + ''_expiration_yr'').value;
                var currentTime  = new Date();
                var currentMonth = currentTime.getMonth() + 1;
                var currentYear  = currentTime.getFullYear();
                if (ccExpMonth < currentMonth && ccExpYear == currentYear) {
                    return false;
                }
                return true;
            }],
     [''validate-cc-cvn'', ''Please enter a valid credit card verification number.'', function(v, elm) {
                var ccTypeContainer = $(elm.id.substr(0,elm.id.indexOf(''_cc_cid'')) + ''_cc_type'');
                if (!ccTypeContainer) {
                    return true;
                }
                var ccType = ccTypeContainer.value;
 
                if (typeof Validation.creditCartTypes.get(ccType) == ''undefined'') {
                    return false;
                }
 
                var re = Validation.creditCartTypes.get(ccType)[1];
 
                if (v.match(re)) {
                    return true;
                }
 
                return false;
            }],
     [''validate-ajax'', '''', function(v, elm) { return true; }],
     [''validate-data'', ''Please use only letters (a-z or A-Z), numbers (0-9) or underscore(_) in this field, first character should be a letter.'', function (v) {
                if(v != '''' && v) {
                    return /^[A-Za-z]+[A-Za-z0-9_]+$/.test(v);
                }
                return true;
            }],
     [''validate-css-length'', ''Please input a valid CSS-length. For example 100px or 77pt or 20em or .5ex or 50%.'', function (v) {
                if (v != '''' && v) {
                    return /^[0-9\.]+(px|pt|em|ex|%)?$/.test(v) && (!(/\..*\./.test(v))) && !(/\.$/.test(v));
                }
                return true;
            }],
     [''validate-length'', ''Text length does not satisfy specified text range.'', function (v, elm) {
                var reMax = new RegExp(/^maximum-length-[0-9]+$/);
                var reMin = new RegExp(/^minimum-length-[0-9]+$/);
                var result = true;
                $w(elm.className).each(function(name, index) {
                    if (name.match(reMax) && result) {
                       var length = name.split(''-'')[2];
                       result = (v.length <= length);
                    }
                    if (name.match(reMin) && result && !Validation.get(''IsEmpty'').test(v)) {
                        var length = name.split(''-'')[2];
                        result = (v.length >= length);
                    }
                });
                return result;
            }],
     [''validate-percents'', ''Please enter a number lower than 100.'', {max:100}],
     [''required-file'', ''Please select a file'', function(v, elm) {
         var result = !Validation.get(''IsEmpty'').test(v);
         if (result === false) {
             ovId = elm.id + ''_value'';
             if ($(ovId)) {
                 result = !Validation.get(''IsEmpty'').test($(ovId).value);
             }
         }
         return result;
     }],
     [''validate-cc-ukss'', ''Please enter issue number or start date for switch/solo card type.'', function(v,elm) {
         var endposition;
 
         if (elm.id.match(/(.)+_cc_issue$/)) {
             endposition = elm.id.indexOf(''_cc_issue'');
         } else if (elm.id.match(/(.)+_start_month$/)) {
             endposition = elm.id.indexOf(''_start_month'');
         } else {
             endposition = elm.id.indexOf(''_start_year'');
         }
 
         var prefix = elm.id.substr(0,endposition);
 
         var ccTypeContainer = $(prefix + ''_cc_type'');
 
         if (!ccTypeContainer) {
               return true;
         }
         var ccType = ccTypeContainer.value;
 
         if([''SS'',''SM'',''SO''].indexOf(ccType) == -1){
             return true;
         }
 
         $(prefix + ''_cc_issue'').advaiceContainer
           = $(prefix + ''_start_month'').advaiceContainer
           = $(prefix + ''_start_year'').advaiceContainer
           = $(prefix + ''_cc_type_ss_div'').down(''ul li.adv-container'');
 
         var ccIssue   =  $(prefix + ''_cc_issue'').value;
         var ccSMonth  =  $(prefix + ''_start_month'').value;
         var ccSYear   =  $(prefix + ''_start_year'').value;
 
         var ccStartDatePresent = (ccSMonth && ccSYear) ? true : false;
 
         if (!ccStartDatePresent && !ccIssue){
             return false;
         }
         return true;
     }]
]);



There are many more validation classes you can assign and I list them here as a reference. For more information on this please use Google, experiment with the code or contact me via my email or the contact form.

validate-select

Please select an option

required-entry

This is a required field

validate-number

Please enter a valid number in this field

validate-digits

Please use numbers only in this field. please avoid spaces or other characters such as dots or commas

validate-alpha

Please use letters only (a-z or A-Z) in this field.

validate-code

Please use only letters (a-z), numbers (0-9) or underscore(_) in this field, first character should be a letter.

validate-alphanum

Please use only letters (a-z or A-Z) or numbers (0-9) only in this field. No spaces or other characters are allowed

validate-street

Please use only letters (a-z or A-Z) or numbers (0-9) or spaces and # only in this field

validate-phoneStrict

Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890

validate-phoneLax

Please enter a valid phone number. For example (123) 456-7890 or 123-456-7890

validate-fax

Please enter a valid fax number. For example (123) 456-7890 or 123-456-7890

validate-date

Please enter a valid date

validate-email

Please enter a valid email address. For example johndoe@domain.com.

validate-emailSender

Please use only letters (a-z or A-Z), numbers (0-9) , underscore(_) or spaces in this field.

validate-password

Please enter 6 or more characters. Leading or trailing spaces will be ignored

validate-admin-password

Please enter 7 or more characters. Password should contain both numeric and alphabetic characters

validate-cpassword

Please make sure your passwords match

validate-url

Please enter a valid URL. http:// is required

validate-clean-url

Please enter a valid URL. For example http://www.example.com or www.example.com

validate-identifier

Please enter a valid Identifier. For example example-page, example-page.html or anotherlevel/example-page

validate-xml-identifier

Please enter a valid XML-identifier. For example something_1, block5, id-4

validate-ssn

Please enter a valid social security number. For example 123-45-6789

validate-zip

Please enter a valid zip code. For example 90602 or 90602-1234

validate-zip-international

Please enter a valid zip code

validate-date-au

Please use this date format: dd/mm/yyyy. For example 17/03/2006 for the 17th of March, 2006

validate-currency-dollar

Please enter a valid $ amount. For example $100.00

validate-one-required

Please select one of the above options.

validate-one-required-by-name

Please select one of the options.

validate-not-negative-number

Please enter a valid number in this field

validate-state

Please select State/Province

validate-new-password

Please enter 6 or more characters. Leading or trailing spaces will be ignored

validate-greater-than-zero

Please enter a number greater than 0 in this field

validate-zero-or-greater

Please enter a number 0 or greater in this field

validate-cc-number

Please enter a valid credit card number.

validate-cc-type

Credit card number doesn''t match credit card type

validate-cc-type-select

Card type doesn''t match credit card number

validate-cc-exp

Incorrect credit card expiration date

validate-cc-cvn

Please enter a valid credit card verification number.

validate-data

Please use only letters (a-z or A-Z), numbers (0-9) or underscore(_) in this field, first character should be a letter.

validate-css-length

Please input a valid CSS-length. For example 100px or 77pt or 20em or .5ex or 50%

validate-length

Maximum length exceeded

示例一:如何控制输入值的长度

通过查找到 /app/code/local/Amasty/Orderattr/Block/Adminhtml/Order/Attribute/Edit/Tab/Main.php

$fieldset->addField(''frontend_class'', ''select'', array(
            ''name''  => ''frontend_class'',
            ''label'' => Mage::helper(''catalog'')->__(''Input Validation''),
            ''title'' => Mage::helper(''catalog'')->__(''Input Validation''),
            ''values''=>  array(
                array(
                    ''value'' => '''',
                    ''label'' => Mage::helper(''catalog'')->__(''None'')
                ),
                array(
                    ''value'' => ''validate-number'',
                    ''label'' => Mage::helper(''catalog'')->__(''Decimal Number'')
                ),
                array(
                    ''value'' => ''validate-digits'',
                    ''label'' => Mage::helper(''catalog'')->__(''Integer Number'')
                ),
                array(
                    ''value'' => ''validate-email'',
                    ''label'' => Mage::helper(''catalog'')->__(''Email'')
                ),
                array(
                    ''value'' => ''validate-url'',
                    ''label'' => Mage::helper(''catalog'')->__(''Url'')
                ),
                array(
                    ''value'' => ''validate-alpha'',
                    ''label'' => Mage::helper(''catalog'')->__(''Letters'')
                ),
                array(
                    ''value'' => ''validate-alphanum'',
                    ''label'' => Mage::helper(''catalog'')->__(''Letters(a-zA-Z) or Numbers(0-9)'')
                ),
/**
 * Added my own here:
 */
                array(
                    ''value'' => ''validate-length minimum-length-0 maximum-length-5'',
                    ''label'' => Mage::helper(''catalog'')->__(''Length - Max 5'')
                ),                
            )
        ));

发现验证长度的样式写法为

validate-length minimum-length-0 maximum-length-5


javascript - 关于Array.prototype.slice.call和Array.prototype.concat.call的问题

javascript - 关于Array.prototype.slice.call和Array.prototype.concat.call的问题

想把通过getelementsbytagname获取到的dom集合转换真实的数组,对于他们产生的结果有点搞不懂(跟自己预想的不一样),测试代码如下
http://runjs.cn/code/i517birf

回复内容:

想把通过getelementsbytagname获取到的dom集合转换真实的数组,对于他们产生的结果有点搞不懂(跟自己预想的不一样),测试代码如下
http://runjs.cn/code/i517birf

concat 如果后面所有参数是数组(包括 this ),才是链接数组返回新的数组,否之只是把这些变量组成一个数组。
splice 要在 this 中删除某些项,而 getElementByTagName 的返回值是只读的,不能删除。
http://zonxin.github.io/post/2015/07/javascript-array-prototype

concat是带参的,所以是

Array.prototype.concat.call(aLi, [])
登录后复制

JavaScript .prototype 如何工作? - How does JavaScript .prototype work?

JavaScript .prototype 如何工作? - How does JavaScript .prototype work?

问题:

I''m not that into dynamic programming languages but I''ve written my fair share of JavaScript code. 我不喜欢动态编程语言,但是我写了相当一部分 JavaScript 代码。 I never really got my head around this prototype-based programming, does any one know how this works? 我从来没有真正了解过这种基于原型的编程,有人知道它是如何工作的吗?

var obj = new Object();
obj.prototype.test = function() { alert(''Hello?''); };
var obj2 = new obj();
obj2.test();

I remember a lot discussion I had with people a while back (I''m not exactly sure what I''m doing) but as I understand it, there''s no concept of a class. 我记得很久以前与人们进行过多次讨论(我不确定自己在做什么),但是据我了解,这里没有一个课堂的概念。 It''s just an object, and instances of those objects are clones of the original, right? 这只是一个对象,这些对象的实例是原始对象的副本,对吗?

But what is the exact purpose of this ".prototype" property in JavaScript? 但是,此 “.prototype” 属性在 JavaScript 中的确切目的是什么? How does it relate to instantiating objects? 它与实例化对象有何关系?

Update: correct way 更新:正确的方法

var obj = new Object(); // not a functional object
obj.prototype.test = function() { alert(''Hello?''); }; // this is wrong!

function MyObject() {} // a first class functional object
MyObject.prototype.test = function() { alert(''OK''); } // OK

Also these slides really helped a lot. 这些幻灯片也确实起到了很大作用。


解决方案:

参考一: https://stackoom.com/question/2P2H/JavaScript-prototype 如何工作
参考二: https://oldbug.net/q/2P2H/How-does-JavaScript-prototype-work

javascript Array.prototype.slice使用说明_javascript技巧

javascript Array.prototype.slice使用说明_javascript技巧

除了正常用法,slice 经常用来将 array-like 对象转换为 true array.

名词解释:array-like object – 拥有 length 属性的对象,比如 { 0: ‘foo'', length: 1 }, 甚至 { length: ‘bar'' }. 最常见的 array-like 对象是 arguments 和 NodeList.

查看 V8 引擎 array.js 的源码,可以将 slice 的内部实现简化为:

复制代码 代码如下:

function slice(start, end) {
var len = ToUint32(this.length), result = [];
for(var i = start; i result.push(this[i]);
}
return result;
}


可以看出,slice 并不需要 this 为 array 类型,只需要有 length 属性即可。并且 length 属性可以不为 number 类型,当不能转换为数值时,ToUnit32(this.length) 返回 0.

对于标准浏览器,上面已经将 slice 的原理解释清楚了。但是恼人的 ie, 总是给我们添乱子:
复制代码 代码如下:

var slice = Array.prototype.slice;
slice.call(); // => IE: Object expected.
slice.call(document.childNodes); // => IE: JScript object expected.

以上代码,在 ie 里报错。可恨 IE 的 Trident 引擎不开源,那我们只有猜测了:
复制代码 代码如下:

function ie_slice(start, end) {
var len = ToUint32(this.length), result = [];

if(__typeof__ this !== ''JScript Object'') throw ''JScript object expected'';
if(this === null) throw ''Oject expected'';

for(var i = start; i result.push(this[i]);
}
return result;
}

至此,把猥琐的 ie 自圆其说完毕。

关于 slice, 还有一个话题:用 Array.prototype.slice 还是 [].slice ? 从理论上讲,[] 需要创建一个数组,性能上会比 Array.prototype 稍差。但实际上,这两者差不多,就如循环里用 i++ 还是 ++i 一样,纯属个人习惯。

最后一个话题,有关性能。对于数组的筛选来说,有一个牺牲色相的写法:
复制代码 代码如下:

var ret = [];
for(var i = start, j = 0; i ret[j++] = arr[i];
}

用空间换时间。去掉 push, 对于大数组来说,性能提升还是比较明显的。

一大早写博,心情不是很好,得留个题目给大家:
复制代码 代码如下:

var slice = Array.prototype.slice;
alert(slice.call({0: ''foo'', length: ''bar''})[0]); // ?
alert(slice.call(NaN).length); // ?
alert(slice.call({0: ''foo'', length: ''100''})[0]); // ?

Javascript Function.prototype.bind详细分析

Javascript Function.prototype.bind详细分析

Function.prototype.bind分析

bind()方法会创建一个新的函数,成为绑定函数。当调用这个绑定函数时,绑定函数会以创建它时传入的第一个参数作为this,传入bind()方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调取原函数。

实际使用中我们经常会碰到这样的问题:

rush:js;"> var name = "pig"; function Person(name){ this.name = name; this.getName = function(){ setTimeout(function(){ console.log("Hello,my name is "+this.name); },100); } } var weiqi = new Person("卫旗"); weiqi.getName(); //Hello,my name is pig

这个时候输出this.name是pig,原因是this的指向是在运行函数时确定的,而不是在定义函数时确定的,再因为setTimeout是在全局环境下只想,所以this就指向了window。

以前解决这个问题的办法通常是缓存this,例如:

rush:js;"> var name = "pig"; function Person(name){ this.name = name; this.getName = function(){ //在这里缓存一个this var self = this; setTimeout(function(){ //在这里是有缓存this的self console.log("Hello,my name is "+self.name); },100); } } var weiqi = new Person("卫旗"); weiqi.getName(); //Hello,my name is 卫旗

这样就解决了这个问题,非常方便,因为它使得setTimeout函数中可以访问Person的上下文。

现在有一个更好的解决办法,可以使用bind()函数,上面的例子可以被更新为:

rush:js;"> var name = "pig"; function Person(name){ this.name = name; this.getName = function(){ setTimeout(function(){ console.log("Hello,my name is "+this.name); }.bind(this),100); //注意上面这一行,添加了bind(this) } } var weiqi = new Person("卫旗"); weiqi.getName(); //Hello,my name is 卫旗

bind()最简单的用法是创建一个函数,使得这个函数无论怎么样调用都拥有同样的this值。JavaScript新手经常犯的一个错误就是将一个方法从一个对象中拿出来,然后再调用,希望方法中的this是原来的对象(比如在回调函数中传入这个方法)。如果不做特殊处理的话,一般会丢失原来的对象。从原来的函数和原来的对象创建一个绑定函数,则可以很漂亮的解决这个问题:

rush:js;"> //定义全局变量x var x = "window"; //在module内部定义x var module = { x:"module",getX:function(){ console.log(this.x); } } module.getX(); //返回module,因为在module内部调用getX()

var getX = module.getX;
getX();
//返回window,因为这个getX()是在全局作用域中调用的

//绑定getX()并将this值设为module
var boundGetX = getX.bind(module);
boundGetX();
//返回module,绑定以后this值始终为module

浏览器支持情况:

browser

很不幸,Function.prototype.bind在IE8及以下版本中不被支持,所以如果没有一个备选方案的话,可能会在运行时出现问题。bind函数在ECMA-262第五版才被加入。它可能不无法在所有浏览器上运行。你可以在脚本部分加入如下代码,让不支持的浏览器也能使用bind()功能。

rush:js;"> if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== "function") { // closest thing possible to the ECMAScript 5 internal IsCallable function throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable"); }

var aArgs = Array.prototype.slice.call(arguments,1),fToBind = this,fnop = function () {},fBound = function () {
return fToBind.apply(this instanceof fnop && oThis
? this
: oThis || window,aArgs.concat(Array.prototype.slice.call(arguments)));
};

fnop.prototype = this.prototype;
fBound.prototype = new fnop();

return fBound;
};
}

语法

rush:js;"> fun.bind(thisArg[,arg1[,arg2[,…]]])

参数

thisArg,当绑定函数被调用时,该参数会作为原函数运行时的this指向,当使用new操作符调用绑定函数时,该参数无效。

arg1,arg2,…,当绑定函数被调用时,这些参数加上绑定函数本身的参数会按照顺序作为原函数运行时的参数。

描述

bind()函数会创建一个新的函数(一个绑定的函数)有同样的函数体(在ECMAScript 5 规范内置Call属性),当该函数(绑定函数的原函数)被调用时this值绑定到bind()的第一个参数,该参数不能被重写。绑定函数被调用时,bind()也接受预设的参数提供给原函数。一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的this值被忽略,同事调用的参数被提供给模拟函数。

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

总结

以上是小编为你收集整理的Javascript Function.prototype.bind详细分析全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

Function.prototype.bindFunction.prototype.bind分析Function.prototype.bind详解详细介绍

JavaScript相关文章

2022最全最新前端面试题(附加解答)
这是我整理所有看过的文章的面试题+各种百度每一道题的答案,希望可以有效的帮助别人本章博客,梳理所有基础的js,jquery,vue,css, html等题,包含面试题,可供参考学习,也督促自我学习
前端面试八股文(详细版)—上
前端面试八股文,知识点广而全,内容会及时更新
Js运算符
JavaScript 语言的算术运算符是使用数字值作为操作数,进行运算之后返回一个数字值。算术运算符+,-,*,/,%% => 模(余数)
【Vue】webpack的基本使用
好处:前端开发自成体系,有一套标准的开发方案和流量。概念: webpack是前端项目工程化的具体解决方案。主要功能:它提供了友好的前端模块化开发支持,以及代码压缩混淆,处理浏览器端JavaScript的兼容性性能优化等强大的功能。好处:让程序员把工作的重心放到具体功能的实现上,提高了前端开发效率和项目的可维护性。注意:目前Vue,React等前端项目,基本上都是基于webpack进行工程化开发的。步骤import和require导入模块的区别1、require对应导出的方法是module.export
Pro3:js实现放大镜效果
JavaScript练习项目第三个:js实现放大镜的效果。
【2022-11-26】JS逆向之北京百姓网
北京百姓网cookie逆向
你评论,我赠书~【TFS-CLUB社区 第9期赠书活动】〖HTML5+CSS3+JavaScript从入门到精通(微课精编版)(第2版)〗等你来拿
你评论,我赠书~【TFS-CLUB社区 第9期赠书活动】〖HTML5+CSS3+JavaScript从入门到精通(微课精编版)〗等你来拿
App逆向案例 X嘟牛 - Frida监听 & WT-JS工具还原(一)
App逆向 X嘟牛 - Frida监听 & WT-JS工具还原(一)
  • • 2022最全最新前端面试题(附加解答)
  • • 前端面试八股文(详细版)—上
  • • Js运算符
  • • 【Vue】webpack的基本使用
  • • Pro3:js实现放大镜效果
  • • 【2022-11-26】JS逆向之北京百姓网
  • • 你评论,我赠书~【TFS-CLUB社区 第9期赠
  • • App逆向案例 X嘟牛 - Frida监听 &
  • • js中的正则表达式入门
  • • JavaScript箭头函数中的this详解
HTMLreactjsCSSNode.jsangulartypescriptvue.jsreact-natispringkotlinAPIseleniumtensorflowbashangularJSexpressxcodematplotlibflaskHibernatedictionaryrailscocoswebnpmreact-hookmongoosegoogle-appformswpfRestwebpackunit-testihttpclassfileNext.jsJsHTML5bootstrap-
  • 友情链接:
  • 菜鸟教程
  • 前端之家
  • 编程小课
  • 小编
  • -
  • 我要投稿
  • -
  • 广告合作
  • -
  • 联系我们
  • -
  • 免责声明
  • -
  • 网站地图
版权所有 © 2018 小编 闽ICP备13020303号-8
微信公众号搜索 “ 程序精选 ” ,选择关注!
微信公众号搜"程序精选"关注
微信扫一扫可直接关注哦!
Version support

我们今天的关于magento 表单验证 Prototype Javascript Validationfrom表单验证的分享就到这里,谢谢您的阅读,如果想了解更多关于javascript - 关于Array.prototype.slice.call和Array.prototype.concat.call的问题、JavaScript .prototype 如何工作? - How does JavaScript .prototype work?、javascript Array.prototype.slice使用说明_javascript技巧、Javascript Function.prototype.bind详细分析的相关信息,可以在本站进行搜索。

本文标签: