Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Option to unmask data on submit #463

Closed
mauricioribeiro opened this issue Oct 13, 2016 · 9 comments
Closed

Option to unmask data on submit #463

mauricioribeiro opened this issue Oct 13, 2016 · 9 comments

Comments

@mauricioribeiro
Copy link

Hi everyone!

First of all, I have to say it is an awesome and useful plugin. It works nicely! However, I was using it in one of my projects and a need appeared: how to setup the plugin options to unmask the data before submit the form?

There is something like that in another mask input plugin called "Inputmask", which is a boolean option named removeMaskOnSubmit. It could be an improvement to this plugin. It's just a suggestion.

Regards

@maurcarvalho
Copy link
Contributor

Hello @mauricioribeiro,

According to the documentation, you can use the method $(selector).cleanVal(); to get the unmasked typed value.

In order to maintain it simple, looks better to remove masks by selectors instead of all masks on submit (removeMaskOnSubmit) like you've mentioned.

Let us know if it's enough to solve your use case 👍

Regards,
@mc

@mc
Copy link

mc commented Dec 13, 2016

whistle

@ibnubay
Copy link

ibnubay commented Dec 21, 2016

Hi @maurcarvalho , when to use $(selector).cleanVal(); ....?
Can u give some example?

I already set on form submit but still cannot get clear mask/clean value...
like this

$("#user_form").submit(function (event) {
            $('.mobile_phone').cleanVal();
        });

Thanks....

@ibnubay
Copy link

ibnubay commented Dec 25, 2016

Update... my earlier code doesn't work.
Because i'm using ajax to load the page, this the coding to be work...

$("#user_form_modal").on("submit", ".js-user-create-form", saveForm);

var saveForm = function () {
        $('.mobile_phone_mask').unmask();
        // This Doesn't work $('.mobile_phone_mask').cleanVal();
};

@igorescobar
Copy link
Owner

Take a look:
screen shot 2016-12-26 at 14 45 24

So this don't remove the mask from your fields. It just get the unmasked value for you. You need to implement this yourself, sorry.

@mauricioribeiro
Copy link
Author

Hi guys,

Thank you for all your help and I'm sorry for answering so late. I solved my problem using html meta-data to store unmasked value through the keydown callback and then I set up the $('form').submit method to iterate all mask input to replace the input value to meta-data value before submit it. I know it seems a little bit weird, but it worked fine.

@ahmadalfy
Copy link

A feature like this will be really necessary ... Otherwise we will have to bind unmask or cleanval every time I want to submit

@Djones4822
Copy link

Djones4822 commented Sep 2, 2022

I found 2 ways to achieve this. First, the reliable way I've determined to check if an input has a mask is to check the $thing.data('mask') property - if this returns an object then we know we need to call unmask() on the input for the value.

In Ajax, I want to call an equivalent to $.fn.serializeArray so I created $.fn.serializeMaskArray() - I copied the jquery source and simply added a check for the mask and to unmask to retrieve the "true" value.

// Everything is extracted from jquery v3.6.0 - constants included within the function for proper execution.
$.fn.extend({
      serializeMaskArray: function() {
                const rCRLF = /\r?\n/g;
                const rsubmittable = /^(?:input|select|textarea|keygen)/i;
                const rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i;
                const rcheckableType = ( /^(?:checkbox|radio)$/i );
		return this.map( function() {
			// Can add propHook for "elements" to filter or add form elements
			var elements = jQuery.prop( this, "elements" );
			return elements ? jQuery.makeArray( elements ) : this;
		} ).filter( function() {
			var type = this.type;
			// Use .is( ":disabled" ) so that fieldset[disabled] works
			return this.name && !jQuery( this ).is( ":disabled" ) &&
				rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
				( this.checked || !rcheckableType.test( type ) );
		} ).map( function( _i, elem ) {

                        // BEGIN ADDITION
                        // Check for mask data property, unmask if found
                        if($(this).data('mask')){
                                return { name: this.name, value: $(this).cleanVal()}
                        }
                        // END ADDITION

			var val = jQuery( this ).val();

			if ( val == null ) {
				return null;
			}
			if ( Array.isArray( val ) ) {
				return jQuery.map( val, function( val ) {
					return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
				} );
			}
			return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
		} ).get();
	}
})

// Usage
console.log($('#my-form).serializeMaskArray())

Also, I had a form that is submitted via browser POST, so for that I just hooked the submit action and unmasked before allowing the submit to continue. Remember, by not calling e.preventDefault() or having a return false the action will continue to bubble.

$(document).ready(()=> {
        $(document).on('submit', '#my-form', (e)=>{
            console.log(e.target);
            $(e.target).find('input').each((i,ele)=>{
                if($(ele).data('mask')){
                    $(ele).unmask()
                }
            })
        })
})

Hope this helps anyone in the future. Let me know if any questions

@douglas-legulas
Copy link

Automation for the unmasking, using event listeners.

  • Works with FormData too
  • Reacts to the reset event.
function Money() {
    this.listeners = {
        submit: undefined,
        formdata: undefined,
        reset: undefined,
    };
}

/**
 * 
 * @param {string} value
 * @returns {Number}
 */
Money.prototype.stringToFloat = function(value) {
    value = value.replace(/[^0-9]/g, '');
    value = value / 100;

    return value;
}

Money.prototype.maskApply = function(input) {
    /**
     * Undocumented way of checking if the mask is applied to an input
     */
    function isMasked(input) {
        return 'undefined' !== typeof $(input).data('mask');
    }

    function setMask(input) {
        if (false === isMasked(input)) {
            $(input).mask('#.##0,00', {reverse: true});
        }
    }

    setMask(input);

    if (input.form) {
        const form = input.form;

        this.listeners.submit = function(event) {
            let value = input.value;

            if (isMasked(input)) {
                value = this.stringToFloat(input.value);
            }

            $(input).unmask();

            input.value = value;
        }.bind(this);

        this.listeners.formdata = function(event) {
            const formdata = event.formData;
            let value = formdata.get(input.name);

            if (isMasked(input)) {
                value = this.stringToFloat(value);
            }

            formdata.set(input.name, value);
        }.bind(this);

        this.listeners.reset = function(event) {
            setMask(input);
        };

        form.addEventListener('submit', this.listeners.submit);
        form.addEventListener('formdata', this.listeners.formdata);
        form.addEventListener('reset', this.listeners.reset);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants