KSK
KSK

Reputation: 636

Input field validation in JavaScript

I have a input field that should accept only these format (d- digit, c- character):

d.d
d.d.d
d.d.c

My code:

var format1 = /[0-9]{1,}\.[0-9]{1,}/g; // d.d
var format2 = /[0-9]{1,}\.[0-9]{1,}\.[0-9]{1,}/g; // d.d.d    
var format3 = /[0-9]{1,}\.[0-9]{1,}\.[a-zA-Z]{1,}/g; // d.d.c    

if (format1.test(input)) {
    format1Con = true;
}
if (format2.test(input)) {
    format2Con = true;
}
if (format3.test(input)) {
    format3Con = true;
}

This code allows some wrong type values. For example - 1.2.3.33, 1.2.ccccc (Here only one character should be aaccepted)

Please help with exact regular expression for my field format.

Upvotes: 1

Views: 56

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627380

You can use

/^\d\.\d+(?:\.(?:\d|[a-z]))?$/i

See demo

The regex matches...

  • ^ - Beginning of a string
  • \d - a digit
  • \. - a literal dot
  • \d+ - 1 or more digits
  • (?:\.(?:\d|[a-z]))? - an optional group matching...
    • \. - literal dot and...
    • (?:\d|[a-z]) - either a single digit or letters from [a-zA-Z] range (since i modifier is used)
  • $ - End of string
    var re = /^\d\.\d+(?:\.(?:\d|[a-z]))?$/; 
    document.write('1.2.3.33: ' + re.test('1.2.3.33') + "<br/>");
    document.write('1.2.ccccc: ' + re.test('1.2.ccccc') + "<br/>");
    document.write('1.2: ' + re.test('1.2') + "<br/>");
    document.write('1.22: ' + re.test('1.22') + "<br/>");
    document.write('1.22.3: ' + re.test('1.22.3') + "<br/>");
    document.write('1.2.3: ' + re.test('1.2.3') + "<br/>");
    document.write('1.2.x: ' + re.test('1.2.x') + "<br/>");

Upvotes: 1

Sebastian Nette
Sebastian Nette

Reputation: 7832

You can modify your RegEXP like this:

var format1 = /^[0-9]{1,}\.[0-9]{1,}$/g; // d.d
var format2 = /^[0-9]{1,}\.[0-9]{1,}\.[0-9]{1,}$/g; // d.d.d    
var format3 = /^[0-9]{1,}\.[0-9]{1,}\.[a-zA-Z]{1,}$/g; // d.d.c    

Where ^ matches the start of the string and $ matches the end of the string.

Upvotes: 1

Related Questions