/    Sign up×
Community /Pin to ProfileBookmark

I want to provide alpha AND numeric string, but not only alpha…

Hello everyone,

I have a field in which I will provide something like “id number”. I want to allow to provide “alphanumeric” or only “numeric” string, but not allow if it’s only “alpha” string.

For example:

732874 <— OK (only numbers)
54de4 <— OK (numbers AND letters)
dwkQA <— NOT ALLOWED ( only letters)

I know I must use regExp /[^A-Za-z0-9]/ , but this allows to provide letters only too.
Do you have any idea how to solve it and help me ?
Thank you in advance. ?

Grzegorz.

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@Troy_IIIMar 02.2015 — are there any other characters allowed there or only /a-zA-Z0-9/

If yes, a simple test for digits in your will get you where you want to /d/, so if there are numbers - its a go.

otherwise use a two step match, where a second step match would again be the /d/ regex.
Copy linkTweet thisAlerts:
@mrhooMar 03.2015 — You can write a regular expression that matches a string if it contains only digits, or only digits and alphas.

var rx=/^((d+[a-zA-Zd]*)|([a-zA-Z]+d+[a-zA-Zd]*))$/;

^matches the start of string

(wrap alternatives between start and end

[B](d[a-zA-Zd]*)[/B] matches a digit followed by alphas or digits

|or

[B]([a-zA-Z]+d+[a-zA-Zd]*)[/B] matches alphas followed by digits followed by alphas or digits

) close the alternatives

$ end of string.



[CODE]function valid_1a(s){
var rx=/^((d[a-zA-Zd]*)|([a-zA-Z]+d+[a-zA-Zd]*))$/;
return s+'= '+rx.test(s);
}[/CODE]

//test

['732874', '54de4', 'dwkQA', 'a1dfr1'].map(valid_1a);

/* returned value: (Array)

732874= true,54de4= true,dwkQA= false,a1dfr1= true

*
/
Copy linkTweet thisAlerts:
@grzechwaauthorMar 03.2015 — Thank you so much for your replies!

mrhoo - this is exactly what I wanted to do, thank you ?

Regards.
×

Success!

Help @grzechwa spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...