javascript cell number validation - javascript

I want to validate cell number using JavaScript.
Here is my code.
if(number.value == "") {
window.alert("Error: Cell number must not be null.");
number.focus();
return false;
}
if(number.length != 10) {
window.alert("Phone number must be 10 digits.");
number.focus();
return false;
}
Here is the issue, when I submit the form with out entering the phone number, it is showing the error cell number must not be null. it works fine.
When I submit the form with cell number less than 10 digits, it is showing phone number must be 10 digits. It is also fine.
The problem is when I submit the form with 10 digits, then also it is showing the error phone number must be 10 digits.
Please help me.
Thank You.
And also need the validation code for only digits for cell number.

If number is your form element, then its length will be undefined since elements don't have length. You want
if (number.value.length != 10) { ... }
An easier way to do all the validation at once, though, would be with a regex:
var val = number.value
if (/^\d{10}$/.test(val)) {
// value is ok, use it
} else {
alert("Invalid number; must be ten digits")
number.focus()
return false
}
\d means "digit," and {10} means "ten times." The ^ and $ anchor it to the start and end, so something like asdf1234567890asdf does not match.

function IsMobileNumber(txtMobId) {
var mob = /^[1-9]{1}[0-9]{9}$/;
var txtMobile = document.getElementById(txtMobId);
if (mob.test(txtMobile.value) == false) {
alert("Please enter valid mobile number.");
txtMobile.focus();
return false;
}
return true;
}
Calling Validation Mobile Number Function HTML Code -

function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert("Please enter only Numbers.");
return false;
}
return true;
}
function ValidateNo() {
var phoneNo = document.getElementById('txtPhoneNo');
if (phoneNo.value == "" || phoneNo.value == null) {
alert("Please enter your Mobile No.");
return false;
}
if (phoneNo.value.length < 10 || phoneNo.value.length > 10) {
alert("Mobile No. is not valid, Please Enter 10 Digit Mobile No.");
return false;
}
alert("Success ");
return true;
}
<input id="txtPhoneNo" type="text" onkeypress="return isNumber(event)" />
<input type="button" value="Submit" onclick="ValidateNo();">

If you type:
if { number.value.length!= 10}...
It will sure work because the value is the quantity which will be driven from the object.

This function check the special chars on key press and eliminates the value if it is not a number
function mobilevalid(id) {
var feild = document.getElementById(id);
if (isNaN(feild.value) == false) {
if (feild.value.length == 1) {
if (feild.value < 7) {
feild.value = "";
}
} else if (feild.value.length > 10) {
feild.value = feild.value.substr(0, feild.value.length - 1);
}
if (feild.value.charAt(0) < 7) {
feild.value = "";
}
} else {
feild.value = "";
}
}

Verify this code :
It works on change of phone number field in ms crm 2016 form .
function validatePhoneNumber() {
var mob = Xrm.Page.getAttribute("gen_phone").getValue();
var length = mob.length;
if (length < 10 || length > 10) {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
if (mob > 31 && (mob < 48 || mob > 57)) {} else {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
}

<script type="text/javascript">
function MobileNoValidation()
{
var phno=/^\d{10}$/
if(textMobileNo.value=="")
{
alert("Mobile No Should Not Be Empty");
}
else if(!textMobileNo.value.match(phno))
{
alert("Mobile no must be ten digit");
}
else
{
alert("valid Mobile No");
}
}
</script>

I used the follow code.
var mobileNumber=parseInt(no)
if(!mobileNumber || mobileNumber.toString().length!=10){
Alert("Please provide 10 Digit numeric value")
}
If the mobile number is not a number, it will give NaN value.

<script>
function validate() {
var phone=document.getElementById("phone").value;
if(isNaN(phone))
{
alert("please enter digits only");
}
else if(phone.length!=10)
{
alert("invalid mobile number");
}
else
{
confirm("hello your mobile number is" +" "+phone);
}
</script>

Related

I have a javascript that checks if my form is valid and it stops checking after a certain field

So I made a form in a table in html and the javascript code checks till the (creditcard.value.length) after that the code doesn't check anything
<script language="javascript" type="text/javascript">
function ispsd(form) {
var passed = false;
if (form.Fullname.value.length < 4) {
alert("Enter a valid Full Name");
} else if (form.Email.value.indexOf("#") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Email.value.indexOf(".") == -1) {
alert("Enter a valid E-mail adress.")
} else if (form.Cardholder.value.length < 3) {
alert("Card Holder name is not Valid.")
} else if (form.Creditcard.value.length != 16) {
alert("Credit card number is not valid.")
} else if (isNan(form.Creditcard.value)) {
alert("Credit card number cannot contain letters.")
} else if (isNan(form.Zip.value)) {
alert("Enter a valid Postal Code.")
} else if ((form.Expyear.value) * 1 < 2021) {
alert("Credit Card has Expired.")
} else if (isNan(form.Expyear.value)) {
alert("Enter a valid Year.")
} else if (form.cvv.value.length != 3) {
alert("Enter a valid CVV.")
} else if (isNan(form.cvv.value)) {
alert("CVV cannot contain letters.")
} else {
passed = true;
}
return passed;
}
</script>
and the thing is when I moved the (form.Expyear.value) * 1 < 2021) above the (form.Creditcard.value.length != 16) the validation worked and when I tried to add all the (else if) above the Credit card check it didn't work
don't know what's the problem
if anyone can help I would be thankful
You can always use console.log() to check what the variable has
function validate(form) {
if (form.Fullname.value.length < 4) {
alert('Enter a valid Full Name');
document.form.Fullname.focus();
return false;
}
if (form.Email.value.indexOf('#') == -1 || form.Email.value.indexOf('.') == -1) {
alert('Enter a valid E-mail adress.');
document.form.Email.focus();
return false;
}
if (form.Cardholder.value.length < 3) {
alert('Card Holder name is not Valid.');
document.form.Cardholder.focus();
return false;
}
console.log(form.Creditcard.value);
if (isNaN(form.Creditcard.value)) {
alert('Credit card number cannot contain letters.');
document.form.Creditcard.focus();
return false;
}
if (form.Creditcard.value.length < 16) {
alert('Credit card number is not valid.');
document.form.Creditcard.focus();
return false;
}
if (isNaN(form.Zip.value)) {
alert('Enter a valid Full Name');
document.form.Zip.focus();
return false;
}
if (isNaN(form.Expyear.value)) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (Number(form.Expyear.value) < 2021) {
alert('Enter a valid Year.');
document.form.Expyear.focus();
return false;
}
if (isNaN(form.cvv.value)) {
alert('CVV cannot contain letters.');
document.form.cvv.focus();
return false;
}
if (form.cvv.value.length != 3) {
alert('Enter a valid Year.');
document.form.cvv.focus();
return false;
}
return true;
}
Try to remove the * 1, not sure what's the purpose there
isNaN, and not isNan
I would also handle it differently, what you need is to return true if they pass, rather than identify errors, for example, the demo here below. For example, it will pass your test if you have more than 16 numbers since you're checking x !== 16
function validate() {
var x, text;
// Get the value of the input field with id="numb"
x = document.getElementById("cc").value;
// If x is Not a Number or less than one or greater than 10
if (!isNaN(x) && x.length > 3 && x.length <= 16) {
text = "Input OK";
} else {
text = "Input not valid";
}
document.getElementById("error").innerHTML = text;
}
<p>Please write only numbers, from 4 to 16 maximum characters</p>
<input type="number" id="cc"/><br>
<span id="error"></span><br>
<input type="submit" onclick="validate()" />
Last but not least, this is so verbose and difficult to maintain, I strongly suggest using a library like this one https://www.npmjs.com/package/validator to handle validation, or even jQuery has .validate() useful function for beginner.

Issue validating input field. (js)

I need the validInput function to check if all input entered are numberic character/
The issue is when the first if statement return true, the function seems to skip the input check.
For example, if I enter 1 for input1, then "a" for input2, -3 for input3, the function will return true and shows the result.
https://codepen.io/regnagleppod/pen/NdWLYx
html:
<label>Starting Number: </label>
<input id="input1" type="text">
<br>
<label>Ending Number: </label>
<input id="input2" type="text">
<br>
<label>Step: </label>
<input id="input3" type="text">
<button onclick="return playButton()" id="play">Display Evens</button>
js:
function playButton(){
run();
if (validInput()){
showResult();
}
};
function validInput(){
var x = document.getElementById("input1").value;
var y = document.getElementById("input2").value;
var z = document.getElementById("input3").value;
if((x == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((y == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
return true;
};
Mohit are correct,
Change the function as follows,
function validInput(){
var x = document.getElementById("startingNum").value;
var y = document.getElementById("endingNum").value;
var z = document.getElementById("step").value;
if((x == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((y == "")||(isNaN(y))||(y <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(z))||(z <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
return true;
};
I have modified your code,please modified code
function playButton(){
run();
if (validInput()){
showResult();
}
};
function validInput(){
var x = document.getElementById("input1").value;
var y = document.getElementById("input2").value;
var z = document.getElementById("input3").value;
if((x == "")||(isNaN(x))||(x <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((y == "")||(isNaN(y))||(y <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(z))||(z <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
return true;
};
your mistake is very trivial you are comparing <=0 and isNaN with the value of x, i.e input1.(value) , Change the 2nd and 3rd if (condition) it will work.
Here is the changed code
if((y == "")||(isNaN(y))||(y <= 0)){
alert("Please enter positive numberic character only.");
return false;
}
if((z == "")||(isNaN(z))||(z <= 0)){
alert("Please enter positive numberic character only.");
return false;
}

Number validation along with decimals in key press event

I am doing validation of number except on case. I am doing validation in key press event.
This is the process how am doing my validation..
Output length = Integral + decimals
Example: Integral = 5, decimals = 3
If user enter five digits then am not allowing to enter 6th digit. (i.e. 12345).
But if he type '.' then after am allowing to 3 decimals (i.e. 12345.678). This is working perfectly.
Am facing the issue with below case.
If user enter 1.234 then he navigating to before '.' place using arrows or by mouse click, then user unable to enter another digit. Because I am checking either the integral part or decimal part match the length then I am returning false.
Can any one help me out this. I can do with key up event, but I am trying to achieve this by key press event only. Is there any way to get the position where user entering the digit, if yes then I can get one solution.
var integral = 5, decimals = 3;
//below code in the key press event
if ([8, 9, 13, 37, 39,46].indexOf(e.keyCode) != -1) {
return true;
} else if (e.keyCode == 190 && !e.shiftKey && decimals) {
_value = $(this).val();
if (_value.indexOf('.') != -1) {
return false;
}
return true;
} else if (48 >= e.keyCode || e.keyCode <= 57) {
_value = $(this).val();
if (decimals) {
_value = _value.split('.');
if (_value[0].length == integral || (_value[1] || '').length == decimals) {
return false;
}
return true;
} else {
if (_value.length == integral) {
return false;
}
return true;
}
}
return false;
I used selectionEnd for getting position of where user is typing the digit. Using that I did it.
var evt = e.target || e.srcElement;
_value = $(evt).val();
if ([8, 9, 13, 37, 39, 46].indexOf(e.keyCode) != -1) {
return true;
}
else if (e.keyCode == 190 && !e.shiftKey && decimals) {
if (_value.indexOf('.') != -1) {
return false;
}
return true;
}
else if (48 >= e.keyCode || e.keyCode <= 57) {
if (decimals) {
var isHavingDot = false;
var dotPosition = '';
if (_value.indexOf('.') != -1) {
isHavingDot = true;
dotPosition = _value.indexOf('.')
}
var length = _value.length;
if (isHavingDot) {
_value = _value.split('.');
if (evt.selectionEnd <= dotPosition) {
if (_value[0].length >= integral) {
return false;
}
}
else if ((_value[1] || '').length >= decimals) {
return false;
}
}
else {
if (_value.length >= integral) {
return false;
}
}
return true;
}
else {
if (_value.length == integral) {
return false;
}
return true;
}
}
return false;
If you already know how to do it with the keyup event, then you should be able to take that code and insert it into the keypress handler and implement it on the value that would be in the input if you pass the value through.
For example (I assume your validation works like in the example):
$("#myinput").keypress(function (e) {
//first figure out what the value would be if the keypress were passed through
var key=(e.which) ? e.which : e.keyCode;
var inputvalue=String.fromCharCode((96 <= key && key <= 105)? key-48 : key)
var caretPos = document.getElementById("myinput").selectionStart;
var currentvalue=$("#myinput").val();
var outputstring=currentvalue.substring(0, caretPos) + inputvalue + currentvalue.substring(caretPos);
//allow decimals through
if (outputstring===".") {
e.preventDefault();
$("#myinput").val("0.");
return false;
}
//cancel keypress if they string already has a decimal
if(key===46) return (outputstring.split(".").length - 1)>2;
//now perform the truncation and validation
e.preventDefault();
var outputvalue=parseFloat(outputstring);
var decpart=Math.trunc((outputvalue- parseInt(outputvalue)) * 1000)/1000;
var intpart=Math.floor(outputvalue);
//perform your test on the output value here - only need to test the integer part, since the decimal part is truncated
var outputtest=String(intpart).length<=5;
if (outputtest){
//insert the value if it looks okay
$("#myinput").val(intpart+decpart);
}
return false;
});

why is my javascript not working on my php page?

I am facing issue with javascript for form validation.
On one of the forms the javascript function is working properly, and when on other form, i am trying to do form validation, but the script does not fire up.. i have tried many times to clear my browser cache and refreshed the page but i am not getting any results.
I would be thankful if anyone reviews it and help spot the issue.
The following is the function that works on my homepage:
<script>
function validate()
{
var uid = document.getElementById("usrname").value;
var pwd = document.getElementById("passwd").value;
if (uid == "" || pwd == "") {
alert("Empty fields not allowed");
return false;
}
else if (uid.length < 4 || uid.length > 20) {
alert("User ID string length should be between 4 - 20");
return false;
}
else if (pwd.length < 6 || pwd.length >20) {
alert("Password length should be between 6 - 20");
return false;
}
return true;
}
</script>
<form name="ulogin" action="login.php" method="post" onSubmit="return validate();">
The following validation code on the other page does not run:
<script>
function regval()
{
var cname = document.getElementById("name1").value;
var email = document.getElementById("email").value;
var phn = document.getElementById("phone").value;
var addr1 = document.getElementById("addr1").value;
var addr2 = document.getElementById("addr2").value;
var city = document.getElementById("city").value;
var state = document.getElementById("state").value;
var country = document.getElementById("country").value;
var uname = document.getElementById("uname").value;
var pwd = document.getElementById("passwd").value;
var cnfp = document.getElementById("cnf_passwd").value;
var secans = document.getElementById("sec_ans").value;
var regex=/^[0-9]+$/;
var alphanum=/^[a-z0-9]+$/i;
if(cname == "" || email == "" || phn == "" || addr1 == "" || addr2 == "" || city == "" || state == "" || state == "" || country == "" || uname == "" || pwd == "" || cnfp == ""|| secans == "") {
alert("Empty fields not allowed");
return false;
}
if (cname.length < 3 || cname.length > 20) {
alert("Name length should be between 4-20 characters.");
return false;
}
if (email.length < 10 || email.length > 50 ) {
alert("email length should be between 10-50 characters.");
return false;
}
if (phn.length < 7 || phn.length > 11 ) {
alert("check phone number length.");
return false;
}
else if (!phn.match(regex)) {
alert("Please check inputs, only numbers are allowed.!");
return false;
}
if (city.toLowerCase() != "surat" || state.toLowerCase() != "gujarat" || country.toLowerCase() != "india") {
alert("Sorry, we only serve in surat currently at the moment..!!");
return false;
}
if (uname.length < 4 || uname.length > 20) {
alert("user name should be between 4 - 20 characters.");
return false;
}
else if (!uname.match(alphanum)) {
alert("only characters A-z 0-9 are allowed.");
return false
}
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
if (pwd != cnfp) {
alert("the passwords do not match, please check and try again.");
return false;
}
if (secans.length < 5 || secans.length > 20) {
alert("please check for security answer length. It should be between 5 to 20 characters.");
return false;
}
return true;
}
</script>
<form name="usreg" action="signup.php" method="POST" onSubmit="return regval();">
the script tags are in the head tags of my webpage.
Thanks in advance.
Missing closing bracket ) Here else if (!pwd.match(alphanum) {
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
Should be
if (pwd.length < 6 || pwd.length > 30) {
alert("password length should be between 6 - 30 characters.");
return false;
}
else if (!pwd.match(alphanum)) {
alert("Only characters A-z 0-9 are allowed.");
return false;
}
Note: Always check browser console log for errors.

how to give validation in javascript where only numbers are allowed to enter in prompt box?

var ratioChange = prompt('Are you sure to change seller ration of this user?');
if(ratioChange != "")
{
$('#clsdywusers_hdnaction').val("SET_SELLER_RATIO");
$('#clsdywusers_seller_ratio').val(ratioChange);
}
else
{
alert('Please enter seller ratio.');
return false;
}
Now here what I want is that I only want to allow users to write digits in prompt box.Please help.
Use javascript input keypress event and check for every typed character if it's a number or not:
function is_numeric(val){
if(val > 47 && val < 58) return true;
else return false;
}
$(".your_input").keypress(function(e){
switch(e.which){
// exclude left and right navigation arrows from check
case 0: case 8:break;
default:
if(is_numeric(parseInt(e.which))) return true;
else{
return false;
}
}
});
Update: with prompt
var ratioChange = prompt('Are you sure to change seller ration of this user?');
if(ratioChange != "" && is_number(ratioChange))
{
$('#clsdywusers_hdnaction').val("SET_SELLER_RATIO");
$('#clsdywusers_seller_ratio').val(ratioChange);
}
else
{
alert('Please enter seller ratio.');
return false;
}
function is_numeric(val){
if(val > 47 && val < 58) return true;
else return false;
}
function is_number(val){
var value= new String(val), singleNumber;
for(var i=0; i < value.length; i++){
singleNumber = 48 + parseInt(value[i]);
if(!is_numeric(singleNumber)) return false;
}
return true;
}
JSBIN

Categories