Magento 2 Form Validation – Validate Input Number and Allow Two Decimal Points with AJAX Submission

form-validationjquerymagento2validation

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?

Best Answer

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>