country code will automatically added before mobile number - javascript

If any one type in input box only number like : 01234567890 (total 13 digit with country code) then automatically add 88 before mobile number but if if anyone number with 8801234567890 it wont added before number. Another one if type 1234567890 total 10 digit then add 880 before number. how to fix it? I tried with add value but its not working. I need only my conditions not every time.
$(document).ready(function() {
$('#phone').keyup(function() {
let total_length = this.value.length;
if(total_length='11'){
$("#phone").val("88"+$("#phone").val());
}
else if(total_length='10'){
$("#phone").val("880"+$("#phone").val());
}
else{
$("#phone").val();
}
});
$.validator.addMethod("countryValid", function(value, element) {
return this.optional(element) || /^(?:\+88|88)?(01[3-9]\d{8})$/i.test(value);
}, "Please enter valid phone no.");
$("#my_form").validate({
rules: {
phone : {
required: true,
number: true,
countryValid: true
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.3/jquery.validate.min.js"></script>
<form id="my_form">
<input type="text" name="phone" id="phone" />
<br><br>
<button type="submit">Submit</button>
</form>

Fixed it with replace keyup to change and add the ==(Equal to) from =(assignment operators)
$('#phone').change(function() {
let total_length = this.value.length;
if(total_length=='11'){
$("#phone").val("88"+$("#phone").val());
}
else if(total_length=='10'){
$("#phone").val("880"+$("#phone").val());
}
else{
$("#phone").val();
}
});
Thanks #CherryDT for this help.

Related

using HTML variables with JavaScript

I'm creating a sign up system and tying to make a code using JavaScript that checks the phone number the user is entering and only allows it to be used if it is 10 characters long.
this is my code so far:
JavaScript:
<script type="text/javascript">
function phoneIsValid()
{
var phoneL = document.getElementById("phone").length;
if (phoneL != 10)
{
document.getElementById("phoneErr").innerHTML = "invalid phone number"
return false;
}
else
{
document.getElementById("phoneErr").innerHTML = "";
return true;
}
}
</script>
HTML:
<input type="text" id="phone" name="phone" />
<a id="phoneErr"></a>
the problem is that it always replys that the phone number is not 10 cahracters long, even if it is. what am I doing wrong? I dont know much Javascript and I cant find a solution on the internet.
You don't even need JS for this:
<form>
<input type="text" minlength="10" maxlength="10" required placeholder="Phone number (10 digits)" />
<button>Send</button>
</form>
function phoneIsValid()
{
var phoneL = document.getElementById("phone").value.length;
if (phoneL != 10)
{
document.getElementById("phoneErr").innerHTML = "invalid phone number"
return false;
}
else
{
document.getElementById("phoneErr").innerHTML = "";
return true;
}
}
function checkPhone() {
if(phoneIsValid()) {
alert('Phone number is valid');
} else {
alert('Phone number is NOT valid');
}
}
<input type="text" id="phone" name="phone" />
<a id="phoneErr"></a>
<button type="button" onclick="checkPhone()">Check it</button>
As mentioned in comments - you need to validate value of the textbox, not textbox itself.
It'd be quite simple
HTML: First create a submit button, so that we can detect when the user submits it
<input type="text" id="phone" name="phone" placeholder='Enter Phone number..'/>
<button id='submit'>Submit</button>
JavaScript:
<script type="text/javascript">
document.getElementById('submit').onclick = function(){ // trigger when button is clicked
let phoneL = document.getElementById('phone').value.length; // get the length of the value
if (phoneL >= 10) { //check if the length is 10 characters or more
alert('Valid phone number!')
} else {
alert('Invalid phone number!')
}
}
</script>
If you need any other help, feel free to let me know
Try getting the length of the "value".
var phoneL = document.getElementById("phone").value.length;
˄

jQuery Greater than and Smaller than check

This is my form:
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
And this my jQuery that's not working:
$('.fms-quote-form').submit(function() {
if ( $('#fms-zip').val() >= 90000 AND <=96162 ) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
How do I (i) check that the value of #fms-zip is greater than 90000 and smaller than 96162 to submit the form, and (ii) redirect the user to another website if any other value is entered?
Look forward to your input :)
Always check the error console - you're assuming syntax that is faulty. AND will be throwing an error - you need &&.
What's more, you can't just specify your higher number and assume JavaScript will know to compare it against the same subject value you compared the lower value against - you have to repeat the subject.
let val = parseInt($('#fms-zip').val());
if (val >= 90000 && val <= 96162 ) { //<-- note 2 references to #val
As #Alessio Cantarella points out, you also need to cast the value to a number - reading the field's value returns a string.
To check if ZIP is greater than 90000 and smaller than 96162, you need to use:
parseInt function to convert #fms-zip's value to an integer
&& logic operator to check that both conditions are valid.
$(function() {
$('.fms-quote-form').submit(function() {
let zip = parseInt($('#fms-zip').val());
let isZipValid = zip >= 90000 && zip <= 96162;
if (isZipValid) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="fms-quote-form" action="https://web.com/quotes" method="get">
<input name="wpf126904_18" id="fms-zip" type="number" placeholder="Enter your Zipcode">
<input type="submit" value="Get My Rates">
</form>
You can try like this -
$(function() {
$('.fms-quote-form').submit(function() {
var valueZip= parseInt($('#fms-zip').val());
if (valueZip >= 90000 && valueZip <= 96162) {
return true;
} else {
window.open('https://smartfinancial.com/auto-insurance-rates', '_blank');
return false;
}
});
});

How can I change HTML5 form validation default error messages for min and max?

I found this answer for changing error message for invalid values How can I change or remove HTML5 form validation default error messages?.
I need to show different message for value less than min and more than max.
<input type="number" name="test" step="any" min="0.01" max="10.0">
If user enters -1, it should say "Please enter positive value".
If user enters 20, it should say "Value cannot be more than 10".
There may be some fancy API-driven way to do it, but if the title is displayed when the input doesn't match a pattern, you can just modify the the title on change.
To support decimals, you'll need some fancier regex.
*I included the form tag so the validation would work in the snippet
document.querySelector('input').addEventListener('change', (e) => {
if (e.target.value > 10) {
e.target.setAttribute('title', "Value cannot be more than 10");
} else if (e.target.value < 0) {
e.target.setAttribute('title', "Please enter a positive value");
} else {
e.target.setAttribute('title', "Please enter a number");
}
})
<form><input type="text" required="" pattern="10|[0-9]" value="" title="This is an error message" /></form>
With the HTML5 form validation (from your link) you can use a custom message by using the invalid event listener on the input element.
var myInput = document.getElementById("myInput");
myInput.addEventListener("invalid", validate);
myInput.addEventListener("keyup", validate);
function validate() {
var val = parseFloat(this.value);
var min = parseFloat(this.min);
var max = parseFloat(this.max);
if (val < min) {
this.setCustomValidity('Please enter a positive number');
} else if (val > max) {
this.setCustomValidity('Value cannot be more than ' + max);
} else {
this.setCustomValidity("");
}
}
<form>
<input id="myInput" type="number" name="test" step="any" min="0.01" max="10.0">
<button type="submit">Submit</button>
</form>

Validating Contact Number in javascript

I am having a textbox and a div in my form like this :
<input type="text" name="NContact" placeholder="New Contact No." id="txtNewContact"/>
<div id="divCheckContact">
Now on every key press of a key in NContact I need to check if the value entered is a number or not and also it is 10 digit number.And display message in the divison
How to do it Please help.
You can add a pattern and title to do this:
<input type="text" pattern="\d{10}" title="Type 10 digits please" />
The above will check for 10 digit number and if it isn't valid the title will be displayed.
Demo
Note: This is part of html5 spec. Will not work for IE 9 and below.
You can also do it in pure js:
var elem = document.getElementById('txtNewContact');
elem.onkeydown = function(){
if(!/\d{10}/.test(elem.value)){
alert("Type 10 digits please");
}
}
use this
Example
$('#txtNewContact').keyup(function(){
var re = isNaN($(this).val());
if(!re)
{
$('#divCheckContact').html("");
}else
{
$('#divCheckContact').html("please enter only numbers");
$(this).val('');
}
if($(this).val().length>10)
{
$('#divCheckContact').html("please enter only ten 10 digits contact no");
return false;
}
});

Validate (Australian) Phone Numbers in Javascript

I need to validate Australian phone numbers (e.g. 02[3-9]\d{7} or 07[3-9]\d{7} or 04[\d]{8}) in JavaScript.
Requirements:
must be 10 digits
no commas
no dashes
no + in front
must begin with 0
At the moment I can validate required fields and email address but I want to add phone number validation.
<html>
<head>
<script type="text/javascript">
function validateForm() {
var x=document.forms["form3"]["name"].value;
if (x==null || x=="") {
alert("Name must be filled out");
return false;
}
var s=document.forms["form3"]["phone"].value;
if (s==null || s=="") {
alert("Please Enter your Phone or Mobile Number - Preferably Phone Number");
return false;
}
var s=document.forms["form3"]["email"].value;
if (s==null || s=="") {
alert("Please Enter a valid email address");
return false;
}
var k=document.forms["form3"]["email"].value;
var atpos=k.indexOf("#");
var dotpos=k.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=k.length) {
alert("Email Address is Not Valid. Please provide your correct email address.");
return false;
}
}
</script>
</head>
<body>
<form action="/thank-you.php" name="form3" method="post" onsubmit="return validateForm();" >
Your name* <input type="text" name="name" />
Phone number* <input type="text" name="phone" />
Email* <input type="text" name="email" />
<input type="submit" value="sumbit" name="submit" class="button" onclick="javascript:return validateMyForm();" /><input type="reset" value="Reset" class="resetbutton" />
</form>
</body>
</html>
Can someone help out?
Here is a regex that I would recomment
var pattern = /^0[0-8]\d{8}$/g;
So input must start with 0, and followed by a digit and it must be one between 0-8. Then it must have 8 more digit numbers.
Valid phone number examples:
0010293999 (ok)
0110293999 (ok)
0210293999 (ok)
0910293999 (nope)
//Implementation
........
var phoneNumber =document.forms["form3"]["phone"].value;
var phonePattern = /^0[0-8]\d{8}$/g;
//phone number is not valid. Please notice that you don't need to check if it's empty or null since Regex checks it for you anyways
if (!phoneNumber.test(phonePattern))
{
alert("Please Enter your Phone or Mobile Number - Preferably Phone Number");
return false;
}
..........
---- Edit
........
var phoneNumber =document.forms["form3"]["phone"].value;
var phonePattern = /^0[0-8]\d{8}$/g;
//phone number is not valid. Please notice that you don't need to check if it's empty or null since Regex checks it for you anyways
if (!phonePattern.test(phoneNumber))
{
alert("Please Enter your Phone or Mobile Number - Preferably Phone Number");
return false;
}
..........
Thanks to Paul Ferrett for this (php not js, but the regex should translate):
<?php
function validate_phone($number) {
$number = preg_replace('/[^\d]/', '', $number);
return preg_match('/^(0(2|3|4|7|8))?\d{8}$/', $number)
|| preg_match('/^1(3|8)00\d{6}$/', $number)
|| preg_match('/^13\d{4}$/', $number);
}
NB: "MIT License"
Take a look at the Javascript RegExp Object and RegExp test() method.
var patt = /04[\d]{8}/g; // Shorthand for RegExp object
var phoneNumber1 = '0412345678';
var result1 = patt.test(phoneNumber1); // result1 is true
var phoneNumber2 = 'abc';
var result2 = patt.test(phoneNumber2); // result2 is false
You can also use the required pattern.
I've never used it before but it looks like this:
<input type="text"
id="phoneNumber"
title="Phone numbers must be 10 digits and start with 0."
required pattern="0[::digit::]{10}"
/>
// It's late, no idea if that's a valid regex or if works with POSIX.
See this html5rocks article for more info:
http://www.html5rocks.com/en/tutorials/forms/html5forms/#toc-validation
Here is a more robust Australian phone regex. Courtesy of this SO question.
let phonePattern = /^(?:\+?(61))? ?(?:\((?=.*\)))?(0?[2-57-8])\)? ?(\d\d(?:[- ](?=\d{3})|(?!\d\d[- ]?\d[- ]))\d\d[- ]?\d[- ]?\d{3})$/
Testing:
0412123123 TRUE
0491579999 TRUE
0491572983 TRUE
0712122123 TRUE
0212122123 TRUE
0000000000 FALSE
5555551234 FALSE
04121231231 FALSE
041212312 FALSE

Categories

Resources