Validate phone number on blur using pattern - javascript

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

Related

Set Function as Compare in Form Validation using Declarative plugin

We are using FormValidation.io for form validations, now we are trying to use the identical validator using the html attributes which is applied via the Declarative plugin.
What we want?
We want the validation to check that confirm field is same as password field if not it should fail validation
<input
class="form-control"
data-fv-not-empty="true"
data-fv-not-empty___message="The password is required"
type="password"
placeholder="Password"
name="password"
id="input-password"
autocomplete="off"
>
<input
class="form-control"
data-fv-identical="true"
data-fv-identical___compare="getPassword()"
data-fv-identical___message="The password and its confirm are not the same"
type="password"
placeholder="Confirm Password"
name="confirm"
id="input-confirm"
autocomplete="off"
>
<script>
function getPassword() {
return $('#input-password').val();
}
</script>
Now the document states we can declare the compare value as both a string or a function that returns string. Now even if we call a function there it still converts the value as string so as per our current code will show the confirm to be invalid until the value of confirm is not equal to "getPassword()" not the output of this function but this exact string.
We would like to know how can we set compare using html attributes. We can achieve the same using the programatic way but we want to make it work using Declarative mode
Documentation links
https://formvalidation.io/guide/validators/identical/
https://formvalidation.io/guide/plugins/declarative/
https://formvalidation.io/updates/
Thanks in advance.
I directly got in touch with the original developer of FormValidation and he stated that this is something we cannot achieve using html attributes.
So we wont be able to achieve this without modifying the core plugin itself.
Hope this helps anyone who was looking for the same answer.
I just run into this problem.
As a workaround I use this trick:
var fv = form.fv;
fv.updateValidatorOption(input.name, 'identical', 'compare', function(){
return inputConfirm.value;
});
Of course in a entry point where I init validation for all forms in a loop I save instance in form prop: form.fv = fv;

Client-side JavaScript field validation

I have a particular scenario that I need a bit of help with in terms of client-side validation.
I have some input fields that are required (not HTML required) but they are identified as required using a class called "requiredInput" and is evaluated on server-side when the user clicks on the submit button.
I, however, would like to validate the input fields client-side when the user moves away from that field and disable submit till all the required fields are filled in.
How do I go about this scenario in order to handle this client-side completely rather than waiting for the server-side submit to perform the validation?
<input type="text" name="lastName" id="lastName" class="requiredInput" tabindex="3">
Note: I don't want to perform the validation on submit, I would like to validate onblur and disable submit till all the required fields are filled in.
You have bunch of JS validation packages that you can find accros the internet.
For now I think one of the best is ParsleyJS. You can use few build-in (and some extra) validators that work perfectly on client side. Ypou can design your own once. There is also possibility to validate field remotly which is also fine if you don't want to send whole the form to the server.
If you wan't a pure js solution and want full control of what exactly is valid you might want to do something like this:
Create a validateInput() function that gets all the input fields, checks if they have content (and whatever other checks you might want to perform) and proceed with enabling the submit button if everything is as expected. Attach that function to the onblur event of each input field.
function validateInput(){
let validInput = true;
let field1Content = document.getElementById('field1').value;
let field2Content = document.getElementById('field2').value;
if(field1Content.length === 0 || field2Content === 0)
validInput = false;
if(validInput)
//enable submit button
}
You can Easly do this if you have Jquery, try below
<input type="text" name="lastName" id="txtbox1" class="requiredInput clsValidate" tabindex="3">
<input type="text" name="lastName" id="txtbox2" class="requiredInput clsValidate" tabindex="3">
<input type="text" name="lastName" id="txtbox3" class="requiredInput clsValidate" tabindex="3">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
ValidateInput();
});
$(document).on('change', 'input.clsValidate[type=text]', function () {
ValidateInput();
});
function ValidateInput() {
var cnt = 0;
$('input.clsValidate[type=text]').each(function (i, obj) {
if ($(this).val().trim().length <= 0) {
cnt++;
}
if (cnt > 0) {
$('#btnsubmit').attr('disabled', 'disabled')
} else {
$('#btnsubmit').removeAttr('disabled');
}
});
}
</script>

HTML Form Field - How to require an input format

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

Regular Expression Issue: custom phone number formatting

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.

Long form validation in JavaScript / jQuery

I have a long long long form. It has about 200 fields. Now, about 50 fields need to be validated through JavaScript / jQuery. How can I easily validate them without a huge amount of code. I want to avoid doing this:
field1 = document.getElementById("field1").value;
if (field1 == '') {
alert ("Please enter a value for Field1");
return false
}
Is there an easier way? Thanks a lot.
Use the jquery Form validation plugin and assign the correct classes to the fields.
It's as simple as class="required" in most cases!
If you just want to check if the field is empty or not you could do something like this using jQuery:
HTML:
<form>
<input class="validate" type="text" />
<input type="text" />
<input class="validate" type="text" />
<input type="text" />
<input class="validate" type="text" />
</form>
SCRIPT:
$('.validate').each(function() { //this will get every input marked with class "validate"
if ($(this).val() == '')
return false;
});
Using JQuery validate plugin can be much help. You can control the way plugin works from your HTML code and even not write any javascript! If you need more complex validatio, you can extend it by adding specific validation functions. It allows you to localize the application as well.
This page gives a good example on how to use the plugin: http://jquery.bassistance.de/validate/demo/milk/ (click the "Show script used on this page" link).
Here is a rudimentary fiddle, that you can use to validate your form, Just add a span after each of the fields that you need to validate.
http://jsfiddle.net/refhat/h2S6G/35/
I thought about this too, but the plugin can be a bit difficult to
use. Do you know if it allows to display an alert box when an error is
found, instead of the actual displaying on the page? That's a bit too
much for this form. Thanks a lot
Here's a validator I wrote that uses a pop-up style alert box for error messages. Is that the sort of thing you are after?
http://validator.codeplex.com/
Do you want default error messages like for required validator? Regarding jquery validate plugin was it the syntax it offers to place validation information in the method call you found difficult since for a large form having validation information located separately from the text boxes makes it harder to go through and verify all fields have the right validators and messages?

Categories