srijan
srijan

Reputation: 1522

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.

Upvotes: 1

Views: 7667

Answers (4)

cimmanon
cimmanon

Reputation: 68319

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.

Upvotes: 0

CME64
CME64

Reputation: 1672

[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

Upvotes: 2

Grim...
Grim...

Reputation: 16953

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/

Upvotes: 4

bastos.sergio
bastos.sergio

Reputation: 6764

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.

Upvotes: 0

Related Questions