Magento form validation using Varien JavaScript objects
Magento form validation using Varien JavaScript objects
When building new pages in Magento, form validation is usually a necessary but highly repetitive process.
Luckily, Magento already comes with very nice form validation functions written in JavaScript.
Here is a quick demo of how to use it, based on the Magento customer login form.
At the end of the .phtml template file, attach the following code:
[codesyntax lang=”javascript” lines=”fancy”]
<script type="text/javascript"> //<![CDATA[ var loginForm = new VarienForm('login-form', true); $('login-email').observe('keypress', bindLoginPost); $('login-password').observe('keypress', bindLoginPost); function bindLoginPost(evt){ if (evt.keyCode == Event.KEY_RETURN) { loginForm.submit(); } } function onepageLogin(button){ if(loginForm.validator && loginForm.validator.validate()){ button.disabled = true; loginForm.submit(); } } //]]> </script>
[/codesyntax]
The key is to wrap a VarienForm object around our form element with id=’login-form’, and then loginForm.validator.validate() will handle everything with ease.
$(‘login-email’).observe(‘keypress’, bindLoginPost) catches Event.KEY_RETURN for each input field. This is good practice, making the form very user friendly.
In order to specify the validation method on each input field, we need to specify the class attribute in the html.
For example, an input field with class=”required-entry validate-password input-text”, the validator will check if the field is empty or the password is strong enough (at least 6 chars as Magento default).
Common validation keywords: validate-password, validate-cpassword (password confirmation), validate-email, etc. A complete list can be found in a full list cam be found under /js/prototype/validation.js
Finally, to put everything together, create a button for onclick=”onepageLogin(this)”
[codesyntax lang=”php” lines=”fancy”]
<button type="button" onclick="onepageLogin(this)" ><span><?php echo $this->__('Login') ?></span></button>
[/codesyntax]
Magento validator saved my day 8)