Javascript/JQuery how to validate phone number - javascript

How to validate input field to enter mobile number and that mobile number should begins with "07" also if some one enter mobile number with space, space should remove on click. . eg: 07 xxxx xxxx onclick it should be 07xxxxxxxx
Now i used html 5 validation method to give warning:
<input type="text" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" pattern="\d{10}">
but this code does not validate it. can someone help me to validate this

When I had to solve the same problem, I used Masked Input Plugin.

You asked me to do it using simple javascript.Here is you answer
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction()
{
var xyz=document.getElementById('mob_no').value.trim();
if(xyz.substr(0,2)==='07')
{
var new_no= document.getElementById('mob_no').value.replace(/\s/g,"")
alert("number after validations check is"+new_no);
}
else
{
alert("incorrect number");
}
}
<input type="text" id="mob_no" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" onblur="myFunction()">
</body>
</html>
Feel free to ask anything and plz repond it worked or not.

Your pattern for accepting telephone number starting with 07 is
<input type="text" name="mobile_number" required="" title="Number format should be 07xxxxxxxx" pattern="^07\d{8}$">
validate 07 at the beginning and after that accept any 8 digit like follow
pattern="^07\d{8}$"

Niles has the right idea.
So, just attach a click handler or a behavior that strips the spaces... ala.
var a = "07989 8989 8 8";
//substitute your element reference ala jQuery('input[name="mobile_number"]');
a = a.replace(/\s+/g,''); // strip the white space
if( /^07\d{8}$/.test(a) ){
// passed test
}else{
// did not pass, show error
}

I believe, like Niles said you would want to use the pattern pattern="^07\d{8}$" which means, in english String starting with "07" ending with any numerical sequence equaling 8 characters
Further more, like James was pointing out, use Javascript to remove your whitespaces. However I would add a interval, to clear them automatically so the user understands how the input works for further usage.
<script type="text/javascript">
var inputElm = document.getElementById('phone_number_id_name'), // id="" name of element
input = inputElm.value;
setInterval(function() { inputElm.value = input.replace(/\s+/g, ''); }, 100); // turncate white-space of input every 100ms
</script>

Related

Validate phone number on blur using pattern

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

Regex on input field for user id syntax [duplicate]

This question already has an answer here:
Learning Regular Expressions [closed]
(1 answer)
Closed 4 years ago.
I have an input field on a registration screen where the user has to enter his user id which is generally 6 characters long. First 2 characters are always alphabets, and the following characters are mostly numbers. (eg. ab123c or xy5678)
How can I check in the input field with jquery / javascript that user only enters in above format before hitting submit.
<input type="text" maxlength="6" name="uid" id="uid" placeholder="enter user id here">
You can validate your input using regex
regex = /^[a-z]{2}[a-z0-9]{4}$/i ;
regex = /^[a-z]{2}[a-z0-9]{4}$/i ;
console.log('ab1234', regex.test('ab1234'));
console.log('abc234', regex.test('abc234'));
console.log('ab1d34', regex.test('ab1d34'));
console.log('ab12e4', regex.test('ab12e4'));
console.log('ab12yz', regex.test('ab12yz'));
console.log('2b1234', regex.test('2b1234'));
console.log('a11234', regex.test('a11234'));
You don't need javascript or jquery. Can use HTML. w3c School
<input type="text" maxlength="6" name="uid" id="uid" placeholder="enter user id here" pattern="[a-zA-z]{2}[a-zA-Z0-9]{4}">
Thanks for the update Barmar, not used it before.
Update:
First I don't know why this is closed. The question isn't about learning regular expression, it's about implementation. Aurelien provides the right answer if you want to use jQuery, mine is if you don't want to use jQuery or javascript. Zohaib ljaz doesn't address the core issue of implementation.
Second: Most of the comments aren't helpful, he does provided examples and it has max-length in the code so of course 6 is the max.
Try this
$('form').on('submit', function(e){
e.preventDefault();
if($('#uid').val().match(/^[a-zA-Z]{2}[a-zA-Z0-9]{4}$/)){
$(this).submit()
}
else {
//Do your error logic here
}
}

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

html & js text field data (DD-MM-YYYY) validation

In my form I have a text field in which user type date. Good habit tells me to not let user to put anything other then dgit and '-' symbol in the field. However i have a bit problem with implementing such feature. So far I Have a field which accept only digits. If user try to put in field letter, this letter is being removed. But the point is to create (DD-MM-YYYY)format so field have to accept '-' symbol. Here is my code:
<input type="text" name="test3" placeholder='DD-MM-YYYY' onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')"/>
i tried put |\- into regex but with no success. Can anyone point me where I am doing mistake?
use thie regex
/^\d{4}-\d{2}-\d{2}$|[^\d-]|-\d{2}-\d*-/
you can also
**/^\d{4}-\d{2}-\d{2}$|[^\d-]|-\d{2}-\d*-/.test(input.value)**
HTML5 has another approach for you:
<input type="date" name="test3">
The browser is responsible for the formatting of the date presentation, though.
You can try something like
<input type="text" name="test3" placeholder='DD-MM-YYYY' onkeyup="if (/[^\d-]/g.test(this.value)) this.value = this.value.replace(/[^\d-]/g,'')" onchange="validate(this)"/>
function validate(el){
var regex = /^(0?[1-9]|[12][0-9]|3[01])-(0?[1-9]|1[012])-\d{4}$/;
if(!regex.test(el.value)){
alert('invalid date');
el.value = '';
}
}
Demo: Fiddle
You can do this with HTML5
see my jsfidle: http://jsfiddle.net/H7tMZ/2/
<form>
<input type="text" name="date" pattern="\d{1,2}-\d{1,2}-\d{4}" placeholder="dd-mm-jjjj"/>
<button type="submit"/>
</form>

Forcing form text to be lower-case

How could I force the text in the "username" text input to be lower-case regardless of what user types?
<div class="register">
<label for="username">Select username:</label>
</div>
<div class="registerform">
<input name="username" class="registerfont" type="text"
id="username" maxlength="15" style="height:35px; width:300px">
</div>
in CSS:
form input[type="text"] {
text-transform: lowercase;
}
otherwise in JS:
var text="this is my text.";
var lowercase=text.toLowerCase();
You have to use javascript. I have an example here: http://jsfiddle.net/xCfdS/3/
HTML:
<input type="text" id="txt" onkeyup="return forceLower(this);"/>​
Javascript:
function forceLower(strInput)
{
strInput.value=strInput.value.toLowerCase();
}​
You can use something as
<input autocapitalize="none" ></input>
and it should work in the latest browsers
For more details check this link
Using jquery assuming that the input ID is username
$(document).ready(function(){
$("#username").on('change keyup paste',function(){
$(this).val($(this).val().toLowerCase());
})
})
#fdiv_bug's answer is good except for the issues mentioned in the comments of their answer. Using the input event instead of the keyup event fixed those issues for me.
HTML:
<input oninput="this.value=this.value.toLowerCase()"/>​
Javascript:
element.addEventListener('input',function(){this.value=this.value.toLowerCase()});​
Combining a bit of everyone's answer to here simplify things.
Use CSS to avoid any flashing and for display purposes.
input[type="username"] {
text-transform: lowercase;
}
Now, because this ONLY effects DISPLAY of the text in the browser, we need to also change the value of the input.
Add an event listener to the input.
const usernameInput = document.querySelector('input[type="username"]');
usernameInput.addEventListener("input", function(e){
e.target.value = e.target.value.toLowerCase();
});
We can send this to the sever like normal and, like others have mentioned, check server-side to make sure a malicious user didn't send us UpPPercaSe input.
This is my suggestion, it's based on the answer from #fdiv-bug & #ali-sheikhpour:
Add text-transform: lowercase; for this field.
input[type="email"] {
text-transform: lowercase;
}
catch "change" event on this field and transform value to lowercase by (String)toLowerCase function.
var upperCaseMatch = /[A-Z]/;
var events = {
CHANGE: 'change'
};
$(function() {
$(document).on('change', 'input[type="email"]', function() {
var value = $(this).val();
if (!upperCaseMatch.test(value)) {
return;
}
$(this).val(value.toLowerCase());
});
});
Hope its useful for you.
I use this simple code :
<input type="text" onkeyup="this.value = this.value.toUpperCase();">
Use onchange instead
<input name="username"
onchange="this.value = this.value.toUpperCase();"
style="text-transform: lowercase; height:35px; width:300px"
class="registerfont"
type="text"
id="username"
maxlength="15"
>
Old question. New answer.
With HTML5 Form Validation now (2021) supported across all major browsers, it is relatively simple to force lowercase text on an input field, client side, using the pattern attribute. (The pattern attribute is supported by all but Opera Mini at the time of writing).
HTML:
<label>Field Name (lowercase letters only)</label>
<input type="text" pattern="[a-z]" placeholder="Field Name (lowercase letters only)">
Note: The below follows from but gets semi out of scope of the question.
Forcing lowercase on an email address field (which is what brought me to this question) seems to be more risky as using pattern/rejex to validate email addresses is fairly complicated and there are potential issues associated with implementing pattern in conjunction with type="email".
The above aside, for my use case, the following pattern was sufficient:
<label>Email Address (lowercase letters only)</label>
<input type="email" pattern="[^A-Z]+" placeholder="Email Address (lowercase letters only)">
The rejex expression [^A-Z]+ allows any characters that aren't capitals. I leave the actual email address validation to the browser via type="email". I tested this on desktop in Chrome, Firefox, Edge and IE11 and all worked fine.
setInterval() will run if the user pastes something in
setInterval(function(){
let myinput = document.getElementById('myinput');
//make lowercase
myinput.value = myinput.value.toString().toLowerCase();
//remove spaces (if you want)
myinput.value = myinput.value.toString().replace(' ', '');
//force specific characters
myinput.value = myinput.value.toString().replace(/[^a-z0-9\/\-_]/, '');
}, 10);
because this is a loop function using .replace(), replacing only first occurrence at a time, but still looping all of them, this appears to animate removing spaces on pasted text.
Using jquery assuming that the input ID is username:
$(document).ready(function(){
$("#username").on('input', function(){
$(this).val( $(this).val().toLowerCase() );
})
});

Categories