简体   繁体   中英

Validation to check if the user has entered the correct format

I have a dynamic grid that has a numeric field in which I have applied masking. Also it has a plus button means the user can add many rows as he wants. The masking is applied like this:

<input  type='textbox' placeholder='00000-00-000' data-mask='00000-00-000' 

This masking is applied when the user enters 10 digit number but it lets the user enter a 2 or 3 digit number as well. For this I am trying to apply validation while saving so that it checks whether the value entered matches the required format.

What I have done so far is:

  value = $(this).find('td:eq(1)').find('input').val();  //saves the entered value in a variable value
               
                myRegExp = new RegExp(/\d{5}-\d{2}-\d{3}/);
               
                if (!myRegExp.test(value)) {
                    valid = false;
                }
                else
                    valid = true;

The value that user enters is saved in varaible called value and then I have defined my Regex Expression to match my value with that expression but somehow this regex expression is not working. Is this the correct way to define regex expression? What am I missing here? My required format is 00000-00-000. Any help would be appreciated.

Your logic is correct but you have not defined the end point that's why it allows to insert more values.

In your Regex it only checks if the 10 digits are in the specific order

try out this

myRegExp = new RegExp(/^\d{5}-\d{2}-\d{3}$/);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM