Magento – How to Validate Special Characters in Magento 2 Validation Mixin

checkoutjavascriptmagento2regexvalidation

I want to validate special characters in a custom validation mixin file (validation-mixin.js)

When I am using this validation mixin for my input field, i.e. a Purchase Order Number in checkout, it shows an error message every time, even though I am using only alphanumeric.

I want for the text field to ONLY accept special characters like
@#$&*()_-{}[]:";',. along with alphanumeric values and white spaces.

Below is my code for validation-mixin.js

define([
    'jquery'
], function ($) {
    "use strict";

    return function () {
        $.validator.addMethod(
            'validate-ponumber-custom',
            function (value) {
                //alert("Data >>> "  +  value);
                // Some custom validation stuff here
                // return utils.isEmptyNoTrim(value) || /^[ \w]{3,}([A-Za-z]\.)?([ \w]*\#\d+)?(\r\n| )[ \w]{3,}/.test(value);
                // return !/p(\s|.){0,2}?o(\s|.){0,2}?.*box|post(\s|.){0,2}?office/i.test(value);
                //return $.mage.isEmptyNoTrim(value) || value.match(/^[0-9 \.-]+$/);
                // return $.mage.isEmptyNoTrim(value) || value.match(/^[ \w]{3,}([A-Za-z]\.)?([ \w]*\#\d+)?(\r\n| )[ \w]{3,}/);
                // return $.mage.isEmptyNoTrim(value) || value.match(/^[a-zA-Z0-9!@#$&()`.+,/"-_:;']*$/);
                // return $.mage.isEmptyNoTrim(value) || value.match(/^[a-zA-Z0-9!@#$&()\`.+,/"-]*$/);
                //return $.mage.isEmptyNoTrim(value) || value.match(/^[a-z]+[a-z0-9_]+$/);
                return $.mage.isEmptyNoTrim(value) || /^[a-zA-Z0-9 ]+$/.test(value);
            },
            $.mage.__('Please use only letters (a-z or A-Z), numbers (0-9), spaces, "#", "$", "&", "(", ")", "-", "_", ":", ";", """, "\'", ",", ".", in this field. Custom >> ')
        );
    }
});

Please let me know which Regular Expression should be used here.

Thanks in advance.

Best Answer

Try this one

define([
    'jquery',
    'mageUtils',
    'Magento_Ui/js/lib/validation/validator',
    'mage/translate'
    ], function ($, utils, validator) {
    'use strict';

    validator.addRule(
        'validate-ponumber-custom',
        function (value) {
            if ($.mage.isEmpty(value)) {
                return true;
            }

            return ^[\s 0-9-_!¡÷?¿,\/\\+=@#$%ˆ^&*(){}|~<>;:"[\]]*$/i.test(value);
        }, $.mage.__('Please enter numbers and special characters.')
    );

    return function () {
        $.validator.addMethod(
            'validate-ponumber-custom',
            function (value, element) {
                return this.optional(element) || ^[\s 0-9-_!¡÷?¿,\/\\+=@#$%ˆ^&*(){}|~<>;:"[\]]*$/i.test(value);
            },
            $.mage.__('Please enter numbers and special characters.')
        );
    }
});

Hope this help

Related Topic