thescientist Posted December 14, 2013 Share Posted December 14, 2013 (edited) I'm trying to write some regex's for some input validation I need to do in an app, and while I can achieve the results I want, I wondering if I can combine or refine the couple regex's I am using to validate the input types I need. 1) Input Type - ID Rules * must start with a letter or number * can contain only letters, numbers, -, ., _, * be between 4 and 15 characters. Should Pass * j.smith_33- Should Fail * aa * jsmith1234567890 * -abc12 Implementation var allowedLength = inputToTest.length >= 4 && inputToTest.length <= 15 ? true : false; if(/^[A-Za-z0-9-_.]+$/.test(inputToTest) && /^[A-Za-z]/.test(inputToTest) && allowedLength){ //passed validation} 2) Input Type - Password * Passwords must be 6-32 characters. * At least one number must be included. Should Pass * abc1-. Should Fail * aabb * bbbcccd * 1234567890ASDFGHJKLQWERTYUIOPZXCV Implementation var allowedLength = inputToTest.length >= 6 && inputToTest.length <= 32 ? true : false; if(/^[A-Za-z0-9-_.]/.test(inputToTest) && /d/.test(inputToTest) && allowedLength){ //passed validation} Any thoughts on trying to combine any of these? In particular would be adding the length requirement to one of these existing regexs. I've tried with playing around with the placement of {4,15} and {6,32} respectively with no luck. Edited December 14, 2013 by thescientist Link to comment Share on other sites More sharing options...
Ingolme Posted December 14, 2013 Share Posted December 14, 2013 The first one would be like this: Starts with one letter or number, then followed by 3 to 14 other characters /[a-zA-Z0-9][a-zA-Z0-9-._]{3,14}/ For the second one, the way you have it is probably the best way. I wouldn't restrict the user's password like this, though: /^[A-Za-z0-9-_.]/.test(inputToTest) Giving the user freedom to use any character is safer. Link to comment Share on other sites More sharing options...
davej Posted December 14, 2013 Share Posted December 14, 2013 (edited) I ended up with something like... var p = /^[A-Za-z0-9][A-Za-z0-9_.-]{3,15}$/;if( p.test("j.smith_33-") ) { alert('passed'); }; Foxy's right, it should be {3,14} Edited December 14, 2013 by davej Link to comment Share on other sites More sharing options...
thescientist Posted December 15, 2013 Author Share Posted December 15, 2013 thanks for the feedback guys, I'll try that out tomorrow. @Ingolme, regarding the allowed password input. I am limited by the virtual keyboard being presented for the particular app I am working. It's basically just alpha, numerics, and those three special characters. Otherwise, yes I totally agree with you. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now