Hikaru Shindo
Hikaru Shindo

Reputation: 2913

How to use regex with can be empty?

I'm doing some easy web application to practice my skill.

I'm using a regex to validate my phone input like this,

var reg = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/;

if(!reg.test($('#input-phone').val())){
    alert('error');
}

It works normally but it can't be empty. I don't know how to modify this to be able to reject empty field.

Upvotes: 0

Views: 105

Answers (2)

Jongware
Jongware

Reputation: 22457

The expression matches an empty string because all of its individual sequences are optional.

The easiest way of ensuring there is some data inside the expression is to add a lookahead for a single character at the start:

var reg = /^(?=.)[\s()+-]*([0-9][\s()+-]*){6,20}$/;

However, it may be easier still to explicitly test if the variable is empty before doing the regex test.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Check whether there is a value if so then use the regex

var reg = /^[\s()+-]*([0-9][\s()+-]*){6,20}$/;
var phone = $('#input-phone').val();
if (phone.length && !reg.test(phone)) {
    alert('error');
}

Upvotes: 2

Related Questions