regex expression in javascript not working as expected - javascript

we are trying to find if the given string is a valid indian mobile number or not
valid indian mobile number
starts with 7 or 8 or 9
followed by 9 same or different numbers
here is my JavaScript for matching it, but unfortunately it returns false even when number is correct
var mobile_number = $('#number').val();
var mobile_regex = new RegExp('/^[789]\d{9}$/');
if(mobile_regex.test(mobile_number) == false) {
console.log("not valid");
} else {
console.log("valid");
}

Your code has two problems. If you're using a RegExp object, you don't need / characters, and the \ character needs to be escaped.
This would work:
var mobile_regex = new RegExp("^[789]\\d{9}");
Alternatively, if you want to use the other format, this would work:
if(!mobile_number.match(/^[789]\d{9}/)) {
console.log("not valid");
} else {
console.log("valid");
}

You can try this
var mobile_number = $('#number').val();
var mobile_regex = new Regex("^[7-9][0-9]{9}$")
if(mobile_regex.test(mobile_number) == false) {
console.log("not valid");
} else {
console.log("valid");
}

Related

Trying to get a prompt to limit the first three character of a prompt to letters only

So i have this code that i want to be able to limit what can be said in a prompt box using javascript. I am using a do and while statement to push out a prompt loop until the prompt meets the requirement, i am only allowed to use javascript. I want the first three characters of the prompt box to be only letters, however i think i have a problem with my regex! any help would be greatly appreciated.
function myFunction() {
var userInput = new Array();
var letters = /^[A-Za-z]+$/;
do {
userInput = prompt('Enter course code');
if (userInput.length != 7) {
alert("The input must contain 7 characters");
}
var userInput3 = userInput.substring(0, 3);
if (userInput3 != /[A-Za-z]+$/){
alert("The first 3 characters must be letters");
}
}
while (userInput.length != 7 && userInput3 != /[A-Za-z]+$/){
}
}
You just compare first 3 letter with string '/[A-Za-z]+$/'
Try this
function myFunction() {
var userInput = new Array();
var letters = /^[A-Za-z]+$/;
do {
userInput = prompt('Enter course code');
if (userInput.length != 7) {
alert("The input must contain 7 characters");
}
var userInput3 = userInput.substring(0, 3);
if (!/^[A-Za-z][A-Za-z][A-Za-z].*/.exec(userInput3)){
alert("The first 3 characters must be letters");
}
}
while (userInput.length != 7 && userInput3 != /[A-Za-z]+$/){
}
}
myFunction()
Using this regex ^[a-zA-Z]{3}.{4}$ you can achieve it in single if loop,
function myFunction() {
var userInput = new Array();
do {
userInput = prompt('Enter course code');
if (!/^[a-zA-Z]{3}.{4}$/.test(userInput)) {
alert("The input must contain 7 characters where first 3 characters must be letters");
}
}
while (!/^[a-zA-Z]{3}.{4}$/.test(userInput)){
}
}
myFunction();
I get the impression you're feeling your way through this at the moment, theres a lot you could do to make your code safer and more efficient in general. while loops are a dangerous way to kill time for a start.
In terms of your regexp problem, try using .test if you're looking for a boolean (true or false) response to your regexp test
For example
/([A-Z]|[a-z])/.test(userInput3)
will return true if all the characters are letters between a to z in lower or upper case ( | is or ).
if you add ! before the test you will reverse its boolean value (true becomes false and vice verse)
so you could go:
if (!/([A-Z]|[a-z])/.test(userInput3)){
/* do something if userInput3 contains anything other than the letters a-z in
upper or lower case */
}
so
You can try the below code.
function myFunction() {
var userInput;
//var regEx = new RegExp("^[a-zA-Z]{3}.{4}$"); // It Will check for first 3 must be characters and length 7
var regEx = new RegExp("^[a-zA-Z]{3}"); // It Will check for first 3 must be characters and not check for length
do {
userInput = prompt('Enter course code');
if (userInput.length != 7) {
alert("The input must contain 7 characters");
}
if (!regEx.test(userInput)){
alert("The first 3 characters must be letters");
}
}
while (userInput.length != 7 && regEx.test(userInput)){
}
}

How to avoid to enter repeated number in input text form?

I'm trying past few days to solve input number form validation in javascript. The logic user doesn't allow to enter repeated same number like "00000000000", "11111111111". If they enter numbers on text field i have to show error message,
sample code,
var mobNumber = $('#phNo').val();
if(mobNumber.match("00000000") || mobNumber.match("1111111")) {
alert('Please enter valid phone number');
}
You could use following regex ^(\d)\1+$ :
^ asserts position at start of the string
(...) 1st capturing group
\d matches a digit (equal to [0-9])
\1 matches the same text as most recently matched by the 1st capturing group
+ Quantifier, matches between one and unlimited times, as many times as possible, giving back as needed
$ asserts position at the end of the string, or before the line terminator right at the end of the string (if any).
See following example:
function test(par){
if(par.match(/^(\d)\1+$/g)){
console.log(par + " is not valid");
}else{
console.log(par + " is valid");
}
}
test("11111111");
test("11131111");
test("111a1111");
test("010101010");
test("9999");
I hope it helps you. Bye
You can simply write code like
$(document).on('input', '#phNo', function() {
var mobNumber = $(this).val();
var res = mobNumber/(mobNumber/10);
if(res == 111111111) {
alert('Please enter valid phone number');
}
});
this is applicable for all numbers and you have to check the max and min length of the input ..
You can try like this,
var phone = "11111111";
var phonecount = phone.length;
var countLength = 0;
for (var i in phone)
{
if(phone.substring(0,1)==phone[i])
{
countLength = countLength + 1;
}
}
if (countLength == phonecount)
alert("Please enter valid phone number");
try this :
var checkPhone = function() {
phone_number = $('#phone').val();
res = (/^(.)\1+$/.test(phone_number) ? '1' : '0');
if(res == '1'){
return 'bad phone number';
} else {
return 'good phone number';
}
}
Test it here : JSFIDDLE

Validate specific format without using "-" to split the string

Hi i need to validate a string before sending my form, the format must be
LLLL999999XXX
Where L is any letter
9 is any number
X is any letter or number.
I figure out how to do this using - to split, the problem is that my users use to enter this value with out the - , so its going to be strage if i ask for a - in the format. (in this moment i ask , pls enter format LLLL-999999-XXX wich is no good.)
How can i validate this, without using - , any ideas? sorry im newbie at javascript
<script language="JavaScript">
function RFC(cual)
{
mensaje = "pls enter this format LLLL-999999-XXX"
pat = /[a-z]|[A-Z]/
pat2 = /[a-z]|[A-Z]|[0-9]/
val = cual.split("-")
if (val.length == 3){
if(val[0].length == 4){
if(!comp(val[0],pat)){
alert( mensaje)
return false
}
}
if(val[1].length == 6){
if(isNaN(val[1])){
alert('no es un numero')
return false
}
}
if(val[2].length == 3){
if(!comp(val[2],pat2)){
alert(mensaje)
return false
}
}
else{
alert(mensaje)
return false
}
}
else{
alert(mensaje)
return false
}
return true
}
function comp(cual,pa){
for(m=0;m<cual.length;m++){
if(!pa.test(cual.charAt(m))){
return false
break
}
}
return true
}
</script>
You could just use the regex as below:
/^[a-z]{4}[0-9]{6}[a-z0-9]{3}$/i
If you want - as optional:
/^[a-z]{4}-?[0-9]{6}-?[a-z0-9]{3}$/i
UPDATED:
var input = "LLLL999999XXX";
var pattern = /^[a-zA-Z]{4}\d{6}[a-zA-Z0-9]{3}$/;
if( input.match(pattern) ){
alert("true");
}else{
alert("false");
}
See the working code at:
JsFiddle

How do I validate a phone number with javascript?

Would someone a little smarter than myself be able to help me with this function? Its purpose is to validate a text input in a form, a phone number field that will only accept 0-9, dash and dot. The HTML calls the function fine.
function validateFeedback() {
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for (i = 0; i < phone.length; i++); {
if (validNumber.indexOf(phone.charAt(i)) == -1); {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
Thanks so much for any help.
Regular expressions should help ;)
I'm sorry I haven't tried to run this code, but it should be OK.
function validateFeedback(){
var phone = document.getElementById("phone");
var RE = /^[\d\.\-]+$/;
if(!RE.test(phone.value))
{
alert("You have entered an invalid phone number");
return false;
}
return true;
}
try like this:
function validateFeedback()
{
var phone = document.getElementById("phone");
var validNumber = "0123456789.-";
for(i = 0; i < phone.length; i++) {
if(validNumber.indexOf(phone.charAt(i)) == -1) {
alert("You have entered an invalid phone number");
return false;
}
}
return true;
}
there are ; out of place ...
I think you should use a regex to do this. Something link this:
function validateFeedback() {
var phone = document.getElementById("phone").value;
var reg = new RegExp("[0-9 .-]*");
return reg.test(phone);
}
If the text input is in a form, you can reference it more directly using the form id and the element id:
var phone = document.<formId>.phone;
What you want to test is the value of the element, so you need:
var phone = document.<formName>.phone.value;
Since the function is probably called from a submit listener on the form, you can make things more efficient using:
<form onsubmit="return validateFeedback(this);" ...>
It also seems to me that a phone number has only digits, not "-" or "." characters, so you should only test for digits 0-9.
So the function can be like:
function validateFeedback(form) {
var phoneValue = form.phone.value;
// Use a regular expression to validate the value
// is only digits
if (/\D/.test(phoneValue) {
// value contains non-digit characters
// advise user of error then
return false;
}
}
you may want to test that the length is reasonable too, but note that phone numbers in different places are different lengths, depending on the location and use of area or country codes, and whether the number is for a mobile, landline or other.
I would prefer to use regular expressions for something like this.
Please look at my modified version of your function which should work in all major browsers without any framework.
function validateFeedback() {
// Get input
var phone = document.getElementById("phone"),
// Remove whitespaces from input start and end
phone = (phone || '').replace(/^\s+|\s+$/g, ''),
// Defined valid charset as regular expression
validNumber = "/^[0123456789.-]+$/";
// Just in case the input was empty
if (phone.length == 0) {
// This depends on your application - is an empty number also correct?
// If not, just change this to "return false;"
return true;
}
// Test phone string against the regular expression
if (phone.match(validNumber)) {
return true;
}
// Some invalid symbols are used
return false;
}
Try this one
function validateFeedback(value) {
var length = value.length;
chk1="1234567890()-+ ";
for(i=0;i<length;i++) {
ch1=value.charAt(i);
rtn1=chk1.indexOf(ch1);
if(rtn1==-1)
return false;
}
return true;
}
function phonenumber(inputtxt)
{
var phoneno = /^\d{10}$/;
if((inputtxt.value.match(phoneno))
{
return true;
}
else
{
alert("message");
return false;
}
}

jQuery validate phone number with with RegEx

I have a simple ajax form and I'm trying to validate that it
has a value
that value is a 10 digit number
I'm trying to use RegEx to do so. Here is what I have so far.
var reg = new RegExp("/[0-9]{10}/");
$("#call_form").bind("submit", function() {
if ($("#call_number").val().length < 1 && reg.test($("#call_number").val())) {
$("#call_error").show();
return false;
}
});
I know the problem has to do witht he RegExp as if I remove this portion of the code it validates that the box has a value.
EDIT: Here is the final regex I'm using
var regEx = new RegExp("/[0-9]/");
$("#call_form").bind("submit", function() {
if ($("#call_number").val().length != 10 && !$("#call_number").val().match(regEx)) {
$("#call_error").show();
$.fancybox.resize();
return false;
}
});
EDIT 2
Using the suggestions here is what i'm usign which allows spaces and dashes that then get stripped on check
$("#call_form").bind("submit", function() {
var Phone = $("#call_number").val().replace(/\D+/g,'');
if (Phone.length != 10) {
$("#call_error").show();
$.fancybox.resize();
return false;
}
});
Here is what I use - its simple, just posting if someone is searching for the same.
var a = PHONE_FROM_FIELD;
var filter = /^[0-9-+]+$/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
Cheers!
Your regex works fine for me... you could shorten it to just /[0-9]{10}/.
Your problem is here:
$("#call_number").val().length < 1. If the number is 10 characters long, it will never be less than 1, no?
You probably meant something like this:
$("#call_number").val().length === 10
No one has said what was wrong with your original effort - it's the slashes (/). When calling RegExp as a constructor, you don't need the slashes (which are a token to indicate a regular expression litteral), e.g.:
var re = /\w+/i;
is equivalent to:
var re = new RegExp('\\w+','i');
Note that you have to quote backslashes for special characters.
One last thing - allow spaces in the number. You might remove them before testing or storing though. Users find it much easier to read numbers in blocks of 3 or 4 digits, e.g.
1234 871 098 is easier to read than 1234871098.
something like this:
var regEx = /^(\+\d)*\s*(\(\d{3}\)\s*)*\d{3}(-{0,1}|\s{0,1})\d{2}(-{0,1}|\s{0,1})\d{2}$/;
$("#call_form").bind("submit", function() {
var val = $("#call_number").val();
if (!val.match(regEx)) {
$("#call_error").show();
return false;
}
});
function validate_Phone_Number() {
var number = $('field_Id').val();
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (filter.test(number)) {
return true;
}
else {
return false;
}
}
use same validation with keypress and keyup using jquery , working for me
jquery code
const goodColor = "#0C6";
const badColor = "#FF0000";
const $mobile_validation = $('#mobile_validation');
$('#mobile').on('keyup keypress', function(e) {
if (e.which == 46 || e.which == 45 || e.which < 48 || e.which > 57) {
event.preventDefault();
}
if(this.value.length !=10 ){
$mobile_validation.text("Please enter 10 digit mobile number ");
$mobile_validation.css("color", badColor);
}
if(this.value.length ===10 ){
$mobile_validation.text("Good!");
$mobile_validation.css("color", goodColor);
}
});
html code
<input type="text" id="mobile" class="form-control" name="telephone" maxlength="10">
<span id="mobile_validation"></span>
// check phone number validation
function validatePhoneNumber(number)
{
count=number.length;
if(number[0]!=" " && number[0]!="-" && number[count-1]!=" " && number[count-1]!="-")
{
temp=number.replace(" ", "");
temp=temp.replace("-", "");
if($.isNumeric(temp))
{
if(temp.length>=7 && temp.length<=12)
{
flag=1;
for(i=1;i<count;i++)
{
if(number[i]=="-" || number[i]==" ")
{
if(number[i-1]=="-" || number[i-1]==" " || number[i+1]=="-" || number[i+1]==" ")
{
flag=0;
}
}
}
if(flag==1)
{
valid=1;
}
else
{
valid=0;
}
}
else
{
valid=0;
}
}
else
{
valid=0;
}
}
else
{
valid=0;
}
return valid;
}

Categories

Resources