`
kirenenko04
  • 浏览: 152321 次
  • 性别: Icon_minigender_2
  • 来自: 上海
社区版块
存档分类
最新评论

Validate Form In Magento

 
阅读更多

I’m sure most fo you will agree that Magento’s frontend validation for form input fields is a nice feature. All it takes is for you to add some CSS classes to the input fields and then upon form submission validation is triggered that outputs, by default, red colored messages that point the possible validation failures etc. This validation is done on the client side via Java Script.

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;
     }]
]);

 

If we extract those from code, here is the list of validations available on client side trough Javascript:

  • IsEmpty
  • validate-select
  • required-entry
  • validate-number
  • validate-digits
  • validate-digits-range
  • validate-alpha
  • validate-code
  • validate-alphanum
  • validate-street
  • validate-phoneStrict
  • validate-phoneLax
  • validate-fax
  • validate-date
  • validate-email
  • validate-emailSender
  • validate-password
  • validate-admin-password
  • validate-cpassword
  • validate-url
  • validate-clean-url
  • validate-identifier
  • validate-xml-identifier
  • validate-ssn
  • validate-zip
  • validate-zip-international
  • validate-date-au
  • validate-currency-dollar
  • validate-one-required
  • validate-one-required-by-name
  • validate-not-negative-number
  • validate-state
  • validate-new-password
  • validate-greater-than-zero
  • validate-zero-or-greater
  • validate-cc-number
  • validate-cc-type
  • validate-cc-type-select
  • validate-cc-exp
  • validate-cc-cvn
  • validate-ajax
  • validate-data
  • validate-css-length
  • validate-length
  • validate-percents
  • required-file
  • validate-cc-ukss

The above mentioned handles the validation of data on the client side. However, client side data can be falsified/manipulated. What we need is the server side validation as well. Let’s check out few examples to see how Magento is handling the server side of the things.

First lets check out the “Customer Account Create” logic. Creating a new customer submits the POST of data to the Mage_Customer_AccountController->createPostAction(). Since customer and customer address are “EAV models”, they have a special way of handling the validation of data, they pass the POST data to the validateData() method of your custom class instance which extends the Mage_Eav_Model_Form class. Below is a code snippet that shows this:

/* @var $customerForm Mage_Customer_Model_Form */
$customer = Mage::getModel('customer/customer');
$customerForm = Mage::getModel('customer/form');
$customerForm->setFormCode('customer_account_create')
    ->setEntity($customer);
$customerData = $customerForm->extractData($this->getRequest());
// ...
$customerErrors = $customerForm->validateData($customerData);

 Validating data on the “data models” is done somewhat different, here the model itself is suppose to implement the validate() method. For example, lets check out the Mage_Review_Model_Review model and the action of saving/creating the review itself, Mage_Review_ProductController->postAction():

public function postAction()
{
    if ($data = Mage::getSingleton('review/session')->getFormData(true)) {
        $rating = array();
        if (isset($data['ratings']) && is_array($data['ratings'])) {
            $rating = $data['ratings'];
        }
    } else {
        $data   = $this->getRequest()->getPost();
        $rating = $this->getRequest()->getParam('ratings', array());
    }
    if (($product = $this->_initProduct()) && !empty($data)) {
        $session    = Mage::getSingleton('core/session');
        /* @var $session Mage_Core_Model_Session */
        $review     = Mage::getModel('review/review')->setData($data);
        /* @var $review Mage_Review_Model_Review */
        $validate = $review->validate();
        if ($validate === true) {
        // ...

 The validate() points to the Mage_Review_Model_Review->validate(), which is implemented into the model itself:

public function validate()
{
    $errors = array();
    $helper = Mage::helper('customer');
    if (!Zend_Validate::is($this->getTitle(), 'NotEmpty')) {
        $errors[] = $helper->__('Review summary can\'t be empty');
    }
    if (!Zend_Validate::is($this->getNickname(), 'NotEmpty')) {
        $errors[] = $helper->__('Nickname can\'t be empty');
    }
    if (!Zend_Validate::is($this->getDetail(), 'NotEmpty')) {
        $errors[] = $helper->__('Review can\'t be empty');
    }
    if (empty($errors)) {
        return true;
    }
    return $errors;
}

 

Add custom validation js function

//<![CDATA[
Validation.add(
	    "validate-greater-than-low","You must input thie field.",
	    function(v){
	        var low_price = parseFloat($$('[name="low_price"]').first().value);
	        var high_price = parseFloat($$('[name="high_price"]').first().value);
	        if (high_price <= low_price && low_price != '') {
	  			return false;
	        } else {
	            return true;
	        }
	    });


Validation.add(
    "validate-textarea-length","Only between  20 to 1000 Characters",
    function(v, elem){
        if(elem.value.length<20 || elem.value.length>1000)
        return false;
        else
        return true;
    });

    //validate-required-by-pr 当 name = price_type 选项=1 的时候必选
Validation.add(
"validate-required-by-pr","This is a required field.",
function(v){
	var price_type = $$('input:checked[type=radio][name=price_type]')[0].value;
	
	if (price_type == '1') {
	  return !Validation.get('IsEmpty').test(v);
	} else {
		return true;
	} 
});

// validate-required-by-oa
Validation.add(
		"validate-required-by-oa","This is a required field.",
		function(v){
			var price_type = $$('input:checked[type=radio][name=price_type]')[0].value;
			
			if (price_type == '2') {
				return !Validation.get('IsEmpty').test(v);
			} else {
				return true;
			} 
		});

// validate-number-pr validate-greater-than-zero-pr

Validation.add(
		"validate-number-pr","This is a required field.",
		function(v){
			 return Validation.get('IsEmpty').test(v) || (!isNaN(parseNumber(v)) && !/^\s+$/.test(parseNumber(v)));
		});
Validation.add(
		"validate-greater-than-zero-pr","This is a required field.",
		function(v){
			if(v.length)
                return parseFloat(v) > 0;
            else
                return true;
		});


Validation.add(
		"validate-file-demand-size","Max File Size allowed is 10M",
		function(v,elm){
			if (!elm.files[0]){
				return true;
			}
			return elm.files[0].size<10*1024*1024;
		});

Validation.add(
		"validate-file-demand-filetype","File type is not allowed",
		function(v,elm){
			if (!elm.files[0]){
				return true;
			}
			var ext=v.toLowerCase().split('.',2);
			return jQuery.inArray(ext[1],['jpg','jpeg','gif','png','bmp','doc','docx','xls','xlsx','ppt','pptx','csv','zip','rar'])>-1;
		});

 

 

分享到:
评论

相关推荐

    validateform

    "validateform"这个主题正是关注于这个方面,确保用户输入的数据符合预设的规则和标准,从而防止错误的数据提交,提高用户体验并保护服务器免受恶意攻击。以下是关于表单验证的一些核心知识点: 1. **前端验证**:...

    比较好用的 FormValidate

    标题中的“比较好用的 FormValidate”指的是一个用于表单验证的工具或库,它可能是一个JavaScript框架,旨在帮助开发者更方便、高效地实现前端或后端的表单数据验证。在网页开发中,表单验证是必不可少的部分,它...

    Jquery validate和form插件

    **jQuery validate 和 form 插件详解** 在网页开发中,用户界面的交互性和数据验证是不可或缺的部分。jQuery 是一个广泛使用的 JavaScript 库,它简化了 DOM 操作、事件处理和动画效果。`jQuery validate` 和 `...

    高质量的jQuery 表单验证插件 Validate Form

    **jQuery Validate Form 插件详解** 在Web开发中,表单验证是不可或缺的一部分,它确保用户输入的数据符合预设的规则,从而保证数据的准确性和安全性。jQuery库为我们提供了便捷的方式来处理DOM操作,同时,jQuery ...

    ValidateForm:使用 jspservlet 进行简单的表单验证

    本项目“ValidateForm”使用Java的JSP(JavaServer Pages)和Servlet技术进行简单的表单验证,旨在帮助初学者理解如何在服务器端处理和验证用户提交的数据。 一、JSP简介 JSP是一种动态网页技术,它允许开发者将...

    Jquery(Validate-Form)使用方法[张振华.Jack]

    ### Jquery(Validate-Form)使用方法详解 #### 一、Jquery Validate 概述 Jquery Validate 是一个非常流行的前端表单验证插件,它由 Jörn Zaefferer 编写和维护,他是 jQuery 团队的一员,同时也是 jQuery UI 的...

    The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3

    Web开发的我们,表单验证是再常见不过的需求了。友好的错误提示能增加用户体验。The best jQuery plugin to validate form fields. Designed to use with Bootstrap 3

    formValidate插件

    **jQuery formValidate 插件详解** `formValidate` 是一个基于 jQuery 的插件,主要用于前端表单验证。在网页开发中,确保用户输入的数据符合预设规则是非常重要的,`formValidate` 插件为此提供了方便易用的解决...

    jquery-form-validate.1.2.zip

    《jQuery Form Validate 1.2:打造高效表单验证》 在Web开发中,表单验证是不可或缺的一环,它确保用户输入的数据符合预设的规则,从而避免无效数据的提交,提高用户体验,同时减轻服务器端的压力。jQuery Form ...

    jquery form validate

    《jQuery Form Validate 深入解析与应用》 在Web开发中,表单验证是必不可少的一环,确保用户输入的数据符合预期格式和规则,避免无效数据的提交,提高用户体验。jQuery Form Validate 是一个广泛使用的轻量级插件...

    jquery-form-validate

    **jQuery Form Validate 框架详解** `jQuery Form Validate` 是一个基于 jQuery 的强大表单验证框架,它为开发者提供了一种简洁、高效的方式来验证用户在网页表单中输入的数据。这个框架使得开发者无需编写复杂的...

    formvalidation.io, FormValidation官方网站.zip

    formvalidation.io, FormValidation官方网站 formvalidation.io这个存储库包含了 formvalidation.io的源代码。安装$ gem install jekyll$ gem install bundler转到 root 目录并安

    jquery-validate验证框架使用详解及JS文件

    《jQuery Validate验证框架详解与JS应用》 在Web开发中,表单验证是不可或缺的一环,它确保用户输入的数据符合预设的规则,避免无效数据的提交,提高用户体验。jQuery Validate是一个强大的验证插件,它简化了...

    formvalidate插件

    "formvalidate插件"正是为了解决这个问题而诞生的,它是一个基于jQuery的表单验证工具,能够帮助开发者轻松实现客户端验证。在本文中,我们将详细探讨formvalidate插件的功能、使用方法及其在实际开发中的应用。 ...

    validate-form:流星形式验证微库

    设置meteor add skinnygeek1010:validate-form 默认情况下,Validate-Form将使事件冒泡直至layout模板。 如果您最顶层的模板没有这样命名,请使用rootLayout标志对其进行配置。 如果需要调试,请添加调试标志以将...

    jQuery formvalidate实现输入不正确时文本框抖动效果

    jQuery formvalidate表单验证效果,当用户输入不正确时,若点击提交按钮的话,则内容不符合规则的文本框会抖动,以提示用户此项输入有问题,有的把抖动形容为摇晃,无所谓,反正是那一类。本表单验证效果形式新颖,...

    validate_form.js: HTML form validation-开源

    在压缩包子文件的文件名列表中,我们看到`validate_form_js-1.9b`,这可能是`validate_form.js` 的一个版本号。版本号中的数字和字母(如1.9b)通常代表软件的不同迭代,其中“b”可能代表“beta”,表示这是测试版...

    Struts1.3.8使用validate 校验日期格式的问题

    Struts1.3.8使用validate 校验yyyyMM日期格式报错 博文链接:https://pharaohsprince.iteye.com/blog/234369

    formValidate ajax bug修改

    `formValidate` 是一个常见的JavaScript表单验证插件,它简化了验证过程,提供了丰富的自定义选项。然而,像任何其他软件一样,`formValidate` 也可能存在一些bug,尤其是在与`ajax`进行交互时。在这个场景中,我们...

    jquery.validate 版本大全

    jquery.validate.1.9.0.min.js jquery.validate.1.12.0.min.js jquery.validate.1.13.1.min.js jquery.validate.1.16.0.min.js jquery.validate.1.14.0.min.js jquery.validate.1.15.1.min.js jquery.validate....

Global site tag (gtag.js) - Google Analytics