1

Code Snippet

<form data-mage-init='{"validation": {}}' data-hasrequired="<?php echo __('* Required Fields') ?>" name="vendor" method="POST" id="vendor" autocomplete="off">
        <div class="well">
        <strong><?php echo __('Enter Height:')?></strong>
        <input type="text"
               id="height" 
               name="height"
               placeholder="Please enter numeric value only"
               data-validate="{required:true, 'validate-number':true}" class="input-text form-control input-md">
            <button type="submit" class="action primary" id="calculateTotalSubmit" name="calculate-total-submit"><?php echo __('Calculate Total')?></button>
        </div>
    </form>

I have given input value required true and validate-number, although it is validating required field input before form is post, it is not validating the required number and showing validation message after form is post. How could I add below validations using Magento 2 form validation rules

As you can see in image, it shows number validation message but form is also submitted.

Number

Using this script to submit form via ajax, validation is not working

<script>
require(['jquery'],function(){
    jQuery(document).ready(function() {

        jQuery("#form-id").submit(function(){
            var height = jQuery("input[name='height']").val();
            var url = "MYURL";
            jQuery.ajax({
                url: url,
                type: "POST",
                data: {height:height},
                showLoader: true,
                cache: false,
                success: function(response){
                    jQuery("#result-data").html(response.output);
                }
            });
            return false;

        });
    });
});
</script>
  • Before form post, validate-number and allow only two digits after decimal point before form is submitted?

2 Answers 2

6

You can use pattern for validate by your own regular expression:

data-validate="{'required':true, 'pattern':/^\d+(\.\d{1,2})?$/, 'validate-greater-than-zero':true}"

You can check validate form using .valid() method:

<script>
    require(['jquery'], function($) {
        $(function() {
            $('#form-id').submit(function() {
                if($('#form-id').valid()) {
                    ... ajax query ...
                }
                return false;
            });
        });
    });
</script>
5
  • I have updated my question with jquery script being used to submit form via ajax. Your regex works fine but it does not validate if I use with this script. How do I check if data-validate true before form submit ? Oct 23, 2017 at 6:27
  • I edited my answer, check please Oct 23, 2017 at 7:27
  • Works like charm. Could you explain the usage of valid() and why do we have to use it ? Also how could I allow more than two decimal points by changing regex pattern ? Oct 23, 2017 at 7:28
  • 1
    Magento validation widget lib/web/mage/validation.js use jquery plugin lib/jquery/jquery.validate.js for work. You can see all plugin's methods at jqueryvalidation.org/documentation/#link-plugin-methods Oct 23, 2017 at 7:48
  • Regex /^\d+(\.\d{1,})?$/ must allow one and more digits after decimal point Oct 23, 2017 at 7:56
0

You can add this js function in your phtml file.

<script type="text/javascript">
function saveForm()
{
    var dataForm = jQuery('#vendor');
    dataForm.mage('validation');
    if (jQuery('#vendor').valid()) {
         jQuery('#calculateTotalSubmit').attr('disabled',true);
         jQuery('#vendor').submit();
    }
}
</script>

you also need to change your button code like below

<button class="action primary" onclick="saveForm()" id="calculateTotalSubmit" name="calculate-total-submit"><?php echo __('Calculate Total')?></button>
2
  • I have already used ` data-mage-init='{"validation": {}}'` default Magento validation classes. How could I achieve without using external jQuery script ? Oct 16, 2017 at 5:50
  • you have to add this syntax for validation var dataForm = jQuery('#vendor'); dataForm.mage('validation'); its default functionality you can refer this blog mageplaza.com/how-to-validate-form-magento-2.html
    – Yogesh
    Oct 16, 2017 at 6:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.