0

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.

2 Answers 2

2

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');
}
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.