Runshax
Runshax

Reputation: 117

validate numeric with 1 special character

i want to validate numeric and allows the + (plus sign), but its not working

what i want

+63443 -> OK
8452 -> OK
s55sd -> Not OK

here's my code

var Nom = $("#addKonId1").val().split(" ").join("").replace(/^\s\s*/, '').replace(/\s\s*$/, '');

var intRegex = /^\d+$/;
if (!intRegex.test(Nom)) {
    alert("wrong Number");

} else {
    alert(Nom);
}

Upvotes: 1

Views: 71

Answers (2)

Kiranramchandran
Kiranramchandran

Reputation: 2094

Try This

var Nom = $("#addKonId1").val().trim(" ");
var intRegex = /^\+?\d+$/;
            if(!intRegex.test(Nom)) {
                alert("wrong Number");

            }
            else{
                alert(Nom);
            } 

DEMO HERE

Upvotes: 2

rink.attendant.6
rink.attendant.6

Reputation: 46218

The regular expression for what you're looking for is:

^\+?\d+$

Which means "a string beginning with optionally one plus sign followed by one or more digits".

Your regex right now only tests for a string beginning with one or more digit characters. Alter intRegex like so:

var intRegex = /^\+?\d+$/;

On a side note, what you're doing in your first line with the replacing can simply be done with trim():

var Nom = $("#addKonId1").val().split(" ").join("").trim();

Upvotes: 1

Related Questions