简体   繁体   中英

How do I force user to enter specific pattern in input field using regex and javascript

I admit, I never explored into the regex albeit knowing its power. And its striking back to me. I am trying to make user enter pattern P99999999 into an input text where P is mandatory while 99999999 can take any digits(not letters). I'm triggering keyup, input field has uppercasing through styling and so far, this is what I have done (I know its too little).

inpt.value = $.trim( inpt.value );
if( inpt.value.indexOf( 'P' ) != 0 )
    inpt.value = inpt.value.replace(/[A-Z]/g, '');

After some exploring I come up with this

[P]+[0-9]+(?:\.[0-9]*)?

I do not know how to validate my input against this. This was generated by an online tool. I know it shouldn't be that hard. Any help.

Try this:

P[0-9]{8}

That's a P, and then any number eight times.

If a P followed by any number of digits is valid, try

P[0-9]+

That's a P, and then any number at least once.

To make sure that this is all they enter, add ^ and $ (as mentioned in the comments):

^P[0-9]+$

A ^ is 'start of input', and the $ is 'end of input'.

So, your final code might be something like:

<input type="text" />
<div class="fail" style="display: none;">Fail!</div>

and

$("input").keyup(function() {
    var patt=/^P[0-9]+$/g;
    var result=patt.test($(this).val());
    if (result) {
        $(".fail").hide();        
    } else {
        $(".fail").show();        
    }
});

http://jsfiddle.net/fuMg4/1/

Finally, make sure you check this on the server side as well. It's easy to bypass client-side validation.

This tool is pretty handy: http://gskinner.com/RegExr/

[updated to fix the stream input (hold key) issue]

here you go

regex [ it might look unconventional as there can be none (*) digits but think again, it is a live validation not the final result validation ]:

^P\d*$

code [edit: simplified ]:

    $('input').on('change keyup keydown',function(){
        var txt = $(this).val();
        $(this).val(/^P\d*$/.test(txt)&txt.length<10?txt:txt.substring(0,txt.length-1));
    });

DEMO

Why don't you use a third party plugin, like jQuery Mask Plugin ...

Requirements like this have been implemented ad nauseum in javascript. You're trying to recreate the wheel, yet again.

Use the pattern attribute

http://cssdeck.com/labs/n8h33j1w

<input type="text" required pattern="^P[0-9]+$" />

input:invalid {
  background: red;
}

input:valid {
  background: green;
}

Be aware that older browsers will need a polyfill (namely, IE), as this is a relatively new property.

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