igorescobar / jQuery-Mask-Plugin

A jQuery Plugin to make masks on form fields and HTML elements.
http://igorescobar.github.io/jQuery-Mask-Plugin/
Other
4.77k stars 1.42k forks source link

Negative Numbers Redux #689

Open Eclipse-Computing opened 6 years ago

Eclipse-Computing commented 6 years ago

Apologies for opening up a new Issue, but I could not re-open the old one.

Much fine work was done in the old Issue, in getting a form field with a negative number to act correctly. Unfortunately, there was just one wrinkle: The entire premise was that the form field always rendered empty, and that the user would fill it in fresh for submission.

Unfortunately, when one loads a value up on page load, and that value is, say, -100, it is actually displayed as -,100. The only way to correct this is to add or remove a zero and then reverse that action.

Here is my JsFiddle: http://jsfiddle.net/rekabis/bhaugrpj/

This is problematic when this feature is used on pages that regularly edit existing content instead of just adding new content. If you edit content, and do not explicitly touch the value in question, any competent validation throws an error upon data entry because -,### is not a number. -### is a number, -#,### is a number, but -,### is not a number. As such, this oversight forces the user to explicitly remove the superfluous comma each and every time the form is used, whether or not that value is actually meant to be edited.

Ideally, the script should check the number upon page load, after the mask has been applied, and re-edit it as needed, but I have no clue how to do this. From what I can tell, this is the last step needed to create the perfect numerical mask.

igorescobar commented 6 years ago

You need to fix the value before initialization. To do this you can use this feature: https://igorescobar.github.io/jQuery-Mask-Plugin/docs.html#mask-as-a-function

This will allow you to do what you want before applying the actual mask. Just make sure that in the end you return a string with the actual mask.