0

I have write a validate rules in jquery which check only digits, now i want to add new validation rules is that first three digit alpha then 6 digit numeric in jquery. How can i do this. here is my only digits validation code here.

$(".mrn").keypress(function (e) { //if the letter is not digit then display error and don't type anything if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { //display error message $("#errmsg").html("Digits Only").show().fadeOut("slow"); return false; } 
3
  • you can use regex. For example Commented Jan 14, 2018 at 12:04
  • i want put first three digit letter,then numeric, how can i with it regex. please give a example. it will better. Commented Jan 14, 2018 at 12:11
  • What about @Transitive's answer? Commented Jan 14, 2018 at 14:01

1 Answer 1

1

I think it is unwise to check as the buttons are pressed whether or not the character pressed is valid. It's better to just check once when the user is done typing and leaves the DOMElement:

$(".mrn").focusout(function() { //Assuming the .mnr class is also the textbox: var input = $(this).val(); var regex = /^\w{3}\d{6}$/; //match against the described pattern. if (!regex.test(input)) { $("#errmsg").html("Digits Only").show().fadeOut("slow"); return false; } return true; }); 

This way the user can make typos and correct it themselves, there is much less code needed to maintain the logic and performance is a bit better tuned.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.