JQuery Phone Number Validation - javascript

I've am using jQuery validation plugin to validate a mobile phone number and am 2/3 of the way there.
The number must:
Not be blank - Done,
Be exactly 11 digits - Done,
Begin with '07' - HELP!!
The required rule pretty much took care of itself and and I managed to find the field length as a custom method that someone had shared on another site.
Here is the custom field length code. Could anyone please suggest what code to add where to also require it begin with '07'?
$.validator.addMethod("phone", function(phone_number, element) {
var digits = "0123456789";
var phoneNumberDelimiters = "()- ext.";
var validWorldPhoneChars = phoneNumberDelimiters + "+";
var minDigitsInIPhoneNumber = 11;
s=stripCharsInBag(phone_number,validWorldPhoneChars);
return this.optional(element) || isInteger(s) && s.length >= minDigitsInIPhoneNumber;
}, "* Your phone number must be 11 digits");
function isInteger(s)
{ var i;
for (i = 0; i < s.length; i++)
{
// Check that current character is number.
var c = s.charAt(i);
if (((c < "0") || (c > "9"))) return false;
}
// All characters are numbers.
return true;
}
function stripCharsInBag(s, bag)
{ var i;
var returnString = "";
// Search through string's characters one by one.
// If character is not in bag, append to returnString.
for (i = 0; i < s.length; i++)
{
// Check that current character isn't whitespace.
var c = s.charAt(i);
if (bag.indexOf(c) == -1) returnString += c;
}
return returnString;
}
$(document).ready(function(){
$("#form").validate();
});

The code in the question seems a very complicated way to work this out. You can check the length, the prefix and that all characters are digits with a single regex:
if (!/^07\d{9}$/.test(num)) {
// "Invalid phone number: must have exactly 11 digits and begin with "07";
}
Explanation of /^07\d{9}$/ - beginning of string followed by "07" followed by exactly 9 digits followed by end of string.
If you wanted to put it in a function:
function isValidPhoneNumber(num) {
return /^07\d{9}$/.test(num);
}
If in future you don't want to test for the prefix you can test just for numeric digits and length with:
/^\d{11}$/

You could use this function:
function checkFirstDigits(s, check){
if(s.substring(0,check.length)==check) return true;
return false;
}
s would be the string, and check would be what you are checking against (i.e. '07').

Thanks for all the answers. I've managed to come up with this using nnnnnn's regular expression. It gives the custom error message when an incorrect value is entered and has reduced 35 lines of code to 6!
$.validator.addMethod("phone", function(phone_number, element) {
return this.optional(element) || /^07\d{9}$/.test(phone_number);
}, "* Must be 11 digits and begin with 07");
$(document).ready(function(){
$("#form").validate();
});
Extra thanks to nnnnnn for the regex! :D

Use indexOf():
if (digits.indexOf('07') != 0){
// the digits string, presumably the number, didn't start with '07'
}
Reference:
indexOf().

Related

Javascript Form validation | set a specific input format

I'm working on a project that has an input field requiring user to enter only any of the following three options:
Number like 150
Number starting with one letter (which must be N, not case sensitive) like N150
Number ending with one letter (which must be N, not case sensitive) like 150N
Any other value like:
150x will return error message wrong input
x150 will return wrong input
1N50 will return wrong position
The correct way to do this is to make an array of valid numbers and then to check if the given text exists on your array.For example:
var validNumbers = [ 150, N150, 150N ];
if (validNumbers.indexOf(parseInt(num, 10)) >=0 ) {
//Match
}
You'll need an indexOf function for IE:
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function(needle) {
for(var i = 0; i < this.length; i++) {
if(this[i] === needle) {
return i;
}
}
return -1;
};
}
check this answer :
Regular expression to match a number range in JavaScript
and adjust to your needs, you can easily add the "N" at the end or at the beginning by adding regex part to make accept values like :
-N150
-150N
-130N
-N130
A non regexapproach (just to show why regex is useful):
function test(value){
//convert to array
value=value.split("");
//check the number
function isnumber(num){
return num.every(n=>"1234567890".includes(n));
}
//weve got three possibilities:
//150
if(isnumber(value)) return true;
//N150
var [n,...rest]=value;
if(n==="N" && isnumber(rest)) return true;
//150N
var n=value.pop();
return n==="N" && isnumber(value);
}
http://jsbin.com/kafivecedi/edit?console

textbox must contain number or letter validation on javascript without regex

Hi guys i got a problem here, how i can validate a password box that must contain at least one numeric character. i'm not allowed using regular expression / regex. i have tried searching over the web, but the solution is always end with regex.
here's my code that i try
function validateIn()
{
var pass=document.getElementById('password').value;
for(var i=0;i<pass.length;i++)
{
if(isNaN(pass.charAt(i))==false)
{
return true;
break;
}
else
{
return false;
}
}
}
i have tried that way but i fail, can u help me guys? thanks before
One possible approach:
function validateIn() {
var pass = document.getElementById('password').value,
p = pass.length,
ch = '';
while (p--) {
ch = pass.charAt(p);
if (ch >= '0' && ch <= '9') {
return true; // we have found a digit here
}
}
return false; // the loop is done, yet we didn't find any digit
}
The point is, you don't have to return immediately after you have found a normal character (as you're basically looking for a single digit) - you just have to move on with your checking.
Note that I have gone without isNaN, as it's a bit inefficient: the only thing required is a range check.

jQuery Validation, Numeric Value Only

I'm trying to validate a form input value. The function below states is the value of the input is a number below 150, show error. Works as it should. However, I want to add to it. If the value contains ANYTHING other than a numeric value AND/OR is a value under 150, show error...
How can I modify?
if ($('.billboard-height').val() < 150) {
$('.sb-billboardalert').fadeIn(600);
}
Since your more thorough validation should be on the server-side anyway, you could just use parseInt or parseFloat depending on what sort of value you are expecting. Then check if the result is actually a number and that it also meets your constraints:
var number = parseFloat($('.billboard-height').val()); // or parseInt depending on expected input
if (isNaN(number) || number < 150) {
$('.sb-billboardalert').fadeIn(600);
}
EDIT:
Based on your comments, you are entering regex land. I gather you only ever want a natural number (and the way parseInt/parseFloat ignores trailing non-numeric characters like px, em, etc. is not ok). How about:
var val = $('.billboard-height').val();
var number = parseInt(val, 10);
if ( ! val.match(/^[0-9]{3,4}$/) || number < 150) {
$('.sb-billboardalert').fadeIn(600);
}
This should only allow natural numbers 150-9999.
I would suggest using regexes:
var intRegex = /^\d+$/;
var floatRegex = /^((\d+(\.\d *)?)|((\d*\.)?\d+))$/;
var str = $('#myTextBox').val();
if(intRegex.test(str) || floatRegex.test(str)) {
alert('I am a number');
...
}
Or with a single regex as per #Platinum Azure's suggestion:
var numberRegex = /^[+-]?\d+(\.\d+)?([eE][+-]?\d+)?$/;
var str = $('#myTextBox').val();
if(numberRegex.test(str)) {
alert('I am a number');
...
}
ref: checking if number entered is a digit in jquery
Don't forget the radix parameter in parseInt():
if (parseInt($('.billboard-height').val(), 10) < 150) {
It's probably faster than using a regex. Regular expressions are not known for being fast, but they are very powerful. It might be overkill for this scenario.
You can try out HTML5's built in form validation:
<input type="number" min="150">
browser support is still pretty shakey though
Any value from an input or select will be a string in javascript. You need to use parseInt() to use operators like > or <. == can be used if you use it to compare to a string like if ($('.billboard-height').val() == "150")
Try parseInt and isNaN functions for check if value is number and less than 150:
var intVal = parseInt($('.billboard-height').val());
if(!isNaN(intVal)){ //not Number
if (parseInt($('.billboard-height').val()) < 150) { //not less than 150
$('.sb-billboardalert').fadeIn(600);
}
}
If you need to support floating point numbers, you can check if a variable is valid using:
function isNumber (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var val = $('.billboard-height').val();
if (isNumber(val) && parseFloat(val) < 150) {
$('.sb-billboardalert').fadeIn(600);
}
If you only need to support integers, use parseInt(n, 10), where 10 is the base to convert the string to.
var val = parseInt($('.billboard-height').val(), 10);
if (val && val < 150) {
$('.sb-billboardalert').fadeIn(600);
}
// Displays an alert if s contains a non-numeric character.
function alertForNonNumeric(s) {
var rgx = /[^0-9]/;
if (s.search(rgx) !== -1) {
alert("Input contains non-numeric characters!");
}
}
JS Fiddle here
NOTE: If you want to check for negative ints as well, you can add a minus sign to the regex:
function alertForNonNumeric(s) {
var rgx = /[^0-9-]/;
if (s.search(rgx) !== -1) {
alert(s + " contains non-numeric characters!");
}
}
I use this solution, I find it quite ellegant - no alerts, user is effectively unable to enter non numeric characters.
This is jQuery example:
function digitsOnly(){
// extract only numbers from input
var num_val = $('#only_numbers').val().match(/\d+/);
$('#only_numbers').val(num_val);
}
Your html:
<input type="text" name="only_numbers" id="only_numbers" on oninput="digitsOnly();"/>

Trouble adding leading zeroes to submitted form data in javascript

I looked through here last night for some examples on adding leading zeroes with JavaScript and I couldn't get any of them to work for my purposes. I want to do this with the data once you hit the submit button. It is running a set of checkers when it does this and this is what I have included, but I grab the POST data in a test php page and the field I am trying to fix shows "undefined"
I need the number of digits to always be 7, regardless of whether they entered a four or five digit number. Leading zeroes need to be added. Not sure if I am kind of close or way off target with this:
function pad(number, length){
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
}
offidlength = custform.optionaldata10.value.length;
if (offidlength <7) {
custform.optionaldata10.value = pad(custform.optionaldata10.value, 7);
}
You forgot the return statement.
return str;
Should be at the end of the function.
edit function should look like:
function pad(number, length){
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
You can make your expression simpler, if you always want 7 digits-
var offid= custform.optionaldata10.value, L= 7-offid.length;
if(L>0) custform.optionaldata10.value= '0000000'.substring(0, L)+offid;

Javascript regex for GMail-style email address validation

I need a regular expression that will accept well-formed emails in several formats (see below) that will be input in a comma-separated list. I have the basic email address
validation regex,
^[\w\d._%+-]+#(?:[\w\d-]+\.)+(\w{2,})(,|$)
which can handle test cases A and B, but not the others. I also tried
^(\<)?[\w\d._%+-]+#(?:[\w\d-]+\.)+(\w{2,})(\>)?(,|$)
which was able to handle A, B, and C, but only validated the first email address in each of test cases D and E. I haven't even gotten to testing a regex for format 3.
tl;dr Need a regex that will validate email addresses 1, 2, and 3.
Good website to test your regular expressions: Online Javascript Regex Tester
Data
Test Cases
A. nora#example.com
B. nora#example.com, fred#example.com
C. <nora#example.com>, fred#example.com
D. <nora#example.com>, <fred#example.com>
E. fred#example.com, <nora#example.com>
Email Address Formats
1. xyz#example.com
2. <xyz#example.com>
3. "xyz"<xyz#example.com>
EDIT
I flagged this as a possible duplicate of:
Validate email address in JavaScript?
which, in turn, seems to be a duplicate of:
Using a regular expression to validate an email address
both of which contain much discussion on the validity of regex as email validation. However, the top-voted regexes provided don't seem to do quite what I want so I don't consider this answered yet.
None of the links or answers provided was the best answer for this question. Here's what solved it:
/*
* regex checks: must start with the beginning of a word or a left caret
* must end with either the end of a word or a right caret
* can handle example.example.com as possible domain
* email username can have + - _ and .
* not case sensitive
*/
var EMAIL_REGEX = /(\<|^)[\w\d._%+-]+#(?:[\w\d-]+\.)+(\w{2,})(\>|$)/i;
var emails = emailList.trim().split(',');
var validEmails = [];
var invalidEmails = [];
for (var i = 0; i < emails.length; i++) {
var current = emails[i].trim();
if(current !== "") {
//if something matching the regex can be found in the string
if(current.search(EMAIL_REGEX) !== -1) {
//check if it has either a front or back bracket
if(current.indexOf("<") > -1 || current.indexOf(">") > -1) {
//if it has both, find the email address in the string
if(current.indexOf("<") > -1 && current.indexOf(">") > -1) {
current = current.substr(current.indexOf("<")+1, current.indexOf(">")-current.indexOf("<") -1);
}
}
}
if(EMAIL_REGEX.test(current)) {
validEmails.push(current);
} else {
invalidEmails.push(current);
}
}
}
It would be simpler to first split the comma-separated list into an array, and validate each member of the array individually. That would make the regex easier to write (and read and maintain), and also give you the ability to provide specific feedback to the user who entered the list ("the 3rd email address is invalid").
So assuming you did that with a split
var bits = csv.split(',');
Iterate through the bits array
for (var i = 0; i < bits.length; ++i) {
if (!validateEmail(bits[i])) {
alert("Email #" + (i+1) + " is bogus");
}
}
Then for the regex, something like this will capture 2 and 3
(\"[a-z0-9\s]+\"\s+)?\<[\w\d._%+-]+#(?:[\w\d-]+\.)+(\w{2,})\>
And you can use the simpler one to capture simple email addresses without the < or the name in quotes in front of it.
A single regex will not necessarily run any faster than two if tests, especially if you short-circuit the or by putting the more likely one first. It's also harder to read and maintain. Lastly it's extra tricky because you need a lookahead: the final > is only ok if the string ahead of the email address includes a < right before the first character of the email.
So my $0.02 = not worth it. Just do two regexes.
This validateEmail function will check for the basic syntax of an email address (xyz#example.com).
The included ifs will check for the alternate formatting (<xyz#example.com>, 'xyz' <xyz#example.com>) and only validate the actual email portion.
Items with only < or > are deemed invalid for poor formatting (Nope#example.com>), same with any emails lacking the basic structure required (invalidExample.com).
var emailList = "abc#example.com,<lmn#example.com>,'xyz' <xyz#example.com>,invalidExample.com,Nope#example.com>,'Still93e-=48%5922=2 Good' <xyz#example.com>";
var emails = emailList.split(",");
//Loop through the array of emails
for (var i = 0; i < emails.length; i++) {
var isValid = 1;
var cur = emails[i];
// If it has a < or a >,
if( cur.indexOf("<") > -1 || cur.indexOf(">") > -1 ){
// Set it invalid
isValid = 0;
// But if it has both < and >
if( cur.indexOf("<") > -1 && cur.indexOf(">") > -1 ){
//Set it valid and set the cur email to the content between < and >
isValid = 1;
cur = cur.substr(cur.indexOf("<")+1, ( cur.indexOf(">") - cur.indexOf("<") - 1 ));
}
}
//Run the validate function
if ( !validateEmail(cur) )
isValid = 0;
// Output your results. valid = 1, not valid = 0
alert("Orig: "+emails[i] +"\nStripped: "+cur+"\nIs Valid: "+isValid);
}
function validateEmail(curEmail){
var emailValid = /.*\#.*\..*$/g;
return (curEmail.test(emailValid));
}
jsFiddle
Will something like this help?
I have tested 2. and 3., and it detects both the patterns.
var isEmail_re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\#[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
function isEmail (s) {
return String(s).search (isEmail_re) != -1;
}
alert(isEmail ('"xyz"<xyz#example.com>'));
http://jsfiddle.net/epinapala/BfKrR/

Categories