I am using regular expression first time, and I really amazed! well, new discovery always amazement :).
I am using in JavaScript. I am using in following manner;(There are many fields and all are working perfectly fine except this phone formatting)
function validate(form) {
var phone = form.phone.value;
var phoneRegex = /^(\+|00)\d{2,3}-\d{1,2}-\d{3}-\d{4}$/g;
//Checking 'phone' and its regular expressions
if(phone == "") {
inlineMsg('phone','<strong>Error</strong><br />You must enter phone number.',2);
return false;
}
if(!phone.match(deptRegex)) {
inlineMsg('phone','<strong>Error</strong><br />Enter valid phone <br />+xxx-x-xxx-xxxx (or) <br />00xxx-x-xxx-xxxx.',2);
return false;
}
return true;
}
HTML
<div id="wrapper">
<form name="form" id="form" class="form" onsubmit="validate(this);return false">
<label for="phone">Phone:</label><input type="text" name="phone" id="phone" />
<input type="submit" value="Submit" class="submit" />
</div>
Now I am confuse that I might wrote the wrong expression but I tested it as well. I think I am mistaken to write the expression in JavaScript. Can someone help?
P.SThe following is the image from a regular expression online tester where I tested the expression.
I can see two problems with your code:
You don't have a closing </form> tag before the last </div>
You're using two different variable names for your regex: phoneRegex and deptRegex.
Once you correct those problems, the code runs fine. Have a look at it working on jsFiddle: http://jsfiddle.net/XFWGk/
If that doesn't work, the problem is probably your inlineMsg function. I'm not familiar with that one, so make sure you're using it correctly.
^(\+|00)\d{2,3}-\d{1,2}-\d{3}-\d{4}$
This matches +nn[n]-n[n]-nnn-nnnn or 0nn[n]-n[n]-nnn-nnnn
What country is that for?
As well as the 00 dial prefix, you might want to also include 011 dial prefix as used from US/Canada.
Related
I have a form and on blur I would like to check if the phone number is in the right format, but it seems to fail every time.
$('.form-control').blur(function(){
if(!this.validity.valid){
$(this).addClass('emptyField');
}
else{
$(this).removeClass('emptyField');
}
})
.emptyField { background:red; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" class="form-control" name="fill_phone" placeholder="xxx-xxx-xxxx" required>
Valid phone numbers should be XXX-XXX-XXXX but it just seems to fail every time. I use the same code on a email field and that will validate just fine.
Is the Content being dynamically rendered ? When I was rendering dynamic content I had to change the syntax to get this to work. here is the syntax you can try. if its not static then j query does not find it with the above syntax. this is what worked for me. This tells jquery to check the page for dynamic content.
S(document).on("blur", ".form-control", event => {
if (!this.validity.valid) {
$(this).addClass("emptyField");
} else {
$(this).removeClass("emptyField");
}
});
OK, So I figured it out and the problem was caused by something unexpected. The form was being included with php. the form had template variables in it like this, value="{fill_phone}".
Before presenting the form to the visitor the template variables were being replace using str_replace, like this, $form = str_replace('{fill_phone}', '', $form); , I would dynamically run through all the variables on the form.
Once I manually removed all the template variables from the form everything worked fine. I would love for someone to explain this to me as I am to a loss why this would break the form validation. Remember the email validation worked fine but the phone number validation was not working for me.
All is working now. Thank you for all your help.
So you need to use a reg ex with JS or HTML5 Validate Pattern. Let me show you two examples.
1
function phonenumber(inputnumber) {
var phone = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
if(inputnumber.value.match(phone)) {
return true;
}
else {
alert("message");
return false;
}
}
HTML5 Validate
In HTML5 you can use <input type='tel'>
<input type='tel'
pattern='[\+]\d{2}[\(]\d{2}[\)]\d{4}[\-]\d{4}'
title='Phone Number
(Format: +99(99)9999-9999)'/>
OR
<label for="phone">Enter your phone number:</label>
<input type="tel" id="phone" name="phone"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"
required>
<small>Format: 123-456-7890</small>
`
Link To MDN HTML5 Phone Input
I'm using the Verify.js library (http://verifyjs.com/). It seems to be exactly what I need to do client side validation.
However, I'm having trouble getting it to work with my regular expressions I'm writing. It seems whenever I try a lookahead, the form is always allowed to be submitted and the regular expression is not evaluated (maybe it's not compiling)?
I believe my regular expression is correct. I'm trying to verify the user input an integer or a decimal.
<form>Type abc
<input required type="text" data-validate="regex(^abc$)" />Type integer/decimal
<input required type="text" data-validate="regex(^[0-9]+([\,\.][0-9]+)?$)" />
<input type="submit" />
Here's a fiddle:
https://jsfiddle.net/ms4pg776/1/
I fixed this by adding a rule to the $.verify variable.
$.verify.addRules({
isIntegerOrDouble: {
regex: /^[0-9]+([\\.][0-9]+)?$/,
message: "Please enter an integer or a decimal number."
}
});
Then in the HTML:
<input required data-validate="isIntegerOrDouble" type="text"/>
Hope it helps someone!
I am trying to use a regular expression to validate an email address. It does not seem to be doing any validation at all. When I load the page the Submit button is disabled because of the $pristine but as soon as I type a letter the button becomes enabled. Also I am aware that the regex is only accepting upper-case at the moment. The following code is my form:
<form name="myForm" ng-hide="email" >
Insert Email : <br/>
<input type="text" name="email" ng-pattern="/^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]
{2,4}$/" ng-model="insert_email" required>
<br/>
<button ng-hide="email"
type="submit"
ng-disabled="myForm.email.$pristine || myForm.email.$invalid">Submit</button>
</form>
I am not sure but I think the problem may lie with the regex itself.
take out the email in myForm.email.$pristine and in myForm.email.$invalid
to look like:
myForm.$pristine
and
myForm.$invalid
also try with ng-required instead of required
It seems to be two things. It looks like the ng-pattern expects an expression instead of a string attribute.
So you need to wrap it in a string if you want to use an inline expression.
Like so:
ng-pattern="'^[A-Z0-9._%+-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}$'"
Also, there seems to be some issues with your regex. I changed it to this:
ng-pattern="'^[a-zA-Z0-9._%+-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$'"
It seems to work.
Plunker Demo
form code:
<form class="form" name ="custRegistration" id="custRegistration" onsubmit="return submitAlbum(this)" action="download.jsp" method="post" >
<p class="email">
<label for="budget">Expected Budget :</label>
<input type="text" name="budget" id="budget"/>
</p>
<p class="submit">
<label for="download" id="freetrail">Download 30 day free trial</label>
<input type="submit" value="Submit" />
</p>
</form>
i want to validate email-ids with the extension which are checked in the above image and block rest of the email-id extensions using javascript..any help would be appreciated??
(\w+\.)*\w+#(\w+\.)+[A-Za-z]+
this regex is email check basic.
you may use regex for this case, follow regex:
((\w+\.)*\w+)#(\w+\.)+(com|kr|net|us|info|biz)
okay , get all the values of checked items in an array (at least this much you should have been able to do by now)
now let the array be ["com","net"]
var arr = ["com","net"];
var str = arr.join("|")
var re = new RegExp("^\w+#\w+\.("+str+")$");
console.log(re);
the regex I have used is the most basic of all, you can change it according to your needs. Another answer on SO suggests "^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" to be a more complete email validator. So you can change your second last line to :
var re = new RegExp("^[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.("+str+")$");
this code will give you the regex you need to validate your email.
Now you can simply do regex test to see which emails pass your validation.
happy coding!
You can also use above regex ( aelor's )as
[a-zA-Z0-9_.+-]+#[a-zA-Z0-9-]+\.(COM|ORG|BIZ|CO)
include your all extentions using pipe separator .
What I want to do here is require that phone numbers be entered into my HTML form as (XXX) XXX-XXXX and that SS Numbers are entered as XXX-XX-XXXX. Thats it.
The only reason I am doing this is so that the form submission results are consistent and easy exported to Excel.
I have been told to use Javascript to do this but perhaps I am not advanced enough to understand all the steps in doing that.
Can someone please point me in the right direction here keeping in mind that I am a beginner?
Wow thank you so much Ethan and #suman-bogati! I am ALMOST there now! The field now pops an error stating to use the correct format of 555-55-5555. Thats great. But no matter what I enter enter into that field the popup persists. I tried 555-55-5555 and also 555555555 and neither are accepted. Here is the HTML for that field:
<label>
Social Security Number:
<input id="ssn" required pattern="^d{3}-d{2}-d{4}$"
title="Expected pattern is ###-##-####" />
</label>
</div>
<script>$('form').on('submit', function(){
$(this).find('input[name="SocialSecurity"]').each(function(){
$(this).val() = $(this).val().replace(/-/g, '');
});
$(this).find('input[name="ssn"]').each(function(){
$(this).val() = $(this).val().replace(/-/g, '');
});
});</script>
<br />
The easiest way to do that is by simply using multiple fields:
<div>
Phone:
(<input type="text" name="phone-1" maxlength="3">)
<input type="text" name="phone-2" maxlength="3">-
<input type="text" name="phone-3" maxlength="4">
</div>
<div>
SSN:
<input type="text" name="ssn-1">-
<input type="text" name="ssn-2">-
<input type="text" name="ssn-3">
</div>
While this approach is certainly easy, it's not great. The user has to press tab or click on each field to enter the data, and there's nothing (other than common sense) from preventing them from entering things other than digits.
I always feel that, when it comes to validation, the less you can get in the user's way, the better. Let them enter their phone number in whatever format they like, then you scrub it, removing everything but digits. That way the user can enter "5555551212" or "(555) 555-1212", but the database will always hold "5555551212".
The other thing to consider is that HTML5 offers some nice specific types for phone numbers (but not SSNs). A modern browser will take care of all the input validation and, even better, mobile devices will show the numeric keypad instead of the whole keypad.
Given that, the best way to display your form is this:
<div>
<label for="fieldPhone">Phone: </label>
<input type="tel" id="fieldPhone" placeholder="(555) 555-1212">
</div>
<div>
<label for="fieldSsn">SSN: </label>
<input type="text" id="fieldSsn" name="ssn" placeholder="555-55-5555" pattern="\d{3}-?\d{2}-?\d{4}">
</div>
If the user has a modern browser, this will handle the user side of the input validation for you. If they don't, you'll have to use a validation library or polyfill. There's a whole list of HTMl5 form validation polyfills here:
https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills#wiki-web-forms
So all that remains is now to normalize your data when you save it to the database.
The ideal place to do that would be the back end; it doesn't say where your form is going, though, so maybe you don't have any say on how things are processed on the back end. So you can do this in the front end instead. For example, using jQuery:
$('form').on('submit', function(){
$(this).find('input[type="tel"]').each(function(){
$(this).val() = $(this).val().replace(/[\s().+-]/g, '');
});
$(this).find('input[name="ssn"]').each(function(){
$(this).val() = $(this).val().replace(/-/g, '');
});
});
This is not a perfect approach either: if you do validation in this function, and the validation fails, the user will see his or her input replaced by the normalized versions, which can be disconcerting.
The best approach would be to use AJAX and .serialize; not only can you have better control over the UI, but you can do all the validation you want. But that's probably a little beyond what you need to do right now.
Note that phone validation is the trickiest. The HTML5 phone validation is very permissive, allowing people to enter international phone numbers, which can have pretty complicated formats. Even people in the US will sometimes enter phone numbers like "+1 (555) 555-1212", and then you have 8 digits instead of 7. If you really want to restrict them to 7 digits, you'll have to add your own custom validation:
/^\(?\d{3}\)?[.\s-]?\d{3}[.\s-]\d{4}$/
This will cover all the common variations people use (periods, spaces, dashes, parentheses), and still allow only 7-digit US phone numbers.
Here's a jsfiddle demonstrating the HTML5 validation and normalization:
http://jsfiddle.net/Cj7UG/1/
I hope this helps!
Use this patterns if you want two patterns should be matched as asked in question.
//for (XXX)-XXX-XXXX
var pattern = /^\(\d{3}\)\-\d{3}\-\d{4}$/;
//for XXX-XXX-XXXX
var pattern2 = /^\d{3}\-\d{3}\-\d{4}$/;
DEMO
Here is a complete solution using jquery and jquery tools validator:
regex pattern that would handle both cases is :
^(\d{3}-|(\d{3})\s)\d{2}-\d{4}$
HTML:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<script src="http://cdn.jquerytools.org/1.2.7/full/jquery.tools.min.js" type="text/javascript"></script>
<link href="http://jquerytools.org/media/css/validator/form.css" type="text/css" rel="stylesheet">
<script>
$(function() {
$("#myform").validator();
});
</script>
</head>
<body>
<form id="myform">
<input type="text" name="name" pattern="^(\d{3}-|\(\d{3}\)\s)\d{2}-\d{4}$" maxlength="30" />
<br>
<input type="submit" name="submit" value="submit" />
</form>
</body>
Click here for demo on jsfiddle
use can use sth like this:
<html>
<head>
</head>
<body>
<input type="text" id="ok">
<script>
document.getElementById("ok").onkeypress = function(e){
var keycodes = new Array(0,48,49,50,51,52,53,54,55,56,57);
var was = false;
for(x in keycodes){
if(keycodes[x] == e.charCode){
was = true;
break;
}
else{
was = false;
};
};
var val = this.value;
if(was === true){
switch(val.length){
case 3:
if(e.charCode !== 0){
this.value += "-";
}
break;
case 6:
if(e.charCode !== 0){
this.value += "-";
}
break;
default:
if(val.length > 10 && e.charCode !== 0){return false;};
break;
};
val += e.charCode;
}
else{
return false;
};
};
</script>
</body>
I tested it in ff