Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex for this format [40]*100+

I am struggling with a Regex for this format [40]*100+ where the user can enter up to 3 digits inside the square brackets and up to 3 next to the multiplication sign. The plus sign can only appear if the previous format of [40]*100 is respected (the plus is optional at the end). And if they extend the input they should be able to extend that format like this [40]*100+[20]*100+[40]*100+ and so on.

This determines if the input is valid but trying to control the format escapes me.

function isValid2(str) {
    return !/[~`!@#$%\^a-zA-Z&()=\-\\\';,/{}\\":<>\?]/g.test(str);
}

$('input.cut_text').on('input change keydown', function () {

    if (isValid2(this.value) == false){
        this.value = this.value.replace(/[^1-9]/g,'');
        return false
   }
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This regexp tests for the format you describe:

/^(\[\d{1,3}\]\*\d{1,3}\+)+$/

\d{1,3} matches up to 3 digits. We put one of these inside literal [], with literal * after that, and literal + after the second one. Then we use a quantified group to allow multiple repetitions.

You can’t do the validation until the user has finished entering the field, because it won’t match the partial value while they’re typing. So you can use it in a change event listener, but not input or keydown.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading