user123456789 user123456789 - 2 months ago 18
jQuery Question

Check the number is in a certain format

I have number that needs to be in a certain format: 123-12345678.
three numbers then a dash then 8 numbers.

I'm already checking that only numbers are entered but how do I check that they enter the correct format?

function Validate(event) {
var regex = new RegExp("^[0-9-]+$");
var str = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (regex.test(str)) {
return true;
} else {
event.preventDefault();
alert("Character " + str + " is not allowed");
return false;
}
}


The validate function is called on the each key press:

<asp:TextBox runat="server" ID="txtNumber" onkeypress="return Validate(event);"></asp:TextBox>

Answer

You can use this regex:

^\d{3}-\d{8}$

Don't check onkeypress just check before submitting.