I was trying to validate my phone number. Everything is working except the validate 10 digit part
if ($(".phone").val() == "") {
phoneerror = "Please enter phone number";
} else if (!($.isNumeric($(".phone").val())) && $(".phone").val() != "") {
phoneerror = "this field cannot contain letters";
} else if ($(".phone").val().length !== 10) {
phoneerror = "Must be 10 Digits";
} else {
phoneerror = "";
}
console.log(phoneerror);
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<input type="text" class="phone" value="12345">
can someone please tell me what is the wrong with my code
Please check this sample. You should position number length before other validations also you can use maxlength html attribute.
function validatePhone(){
if($(".phone").val() == ""){
phoneerror = "Please enter phone number";
} else if ($(".phone").val().length !== 10){
phoneerror = "Must be 10 Digits";
} else if(!($.isNumeric($(".phone").val())) && $(".phone").val() != ""){
phoneerror = "this field cannot contain letters";
}else {
phoneerror = "";
}
console.log(phoneerror);
return phoneerror;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="phone" type="text" onkeyup="validatePhone(this);" maxlength="10"/>
Related
I wrote this code for validate password and i need to show user two different alerts.
(pw.length < 8) when this condition executed "Password need minimum 8 characters"
(pw != cpw) "Passwords does not match"
I already tried all if statements but it not gonna help.
<script>
function validatePassword(){
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
if((pw.length < 8)||(pw != cpw))
{
alert("please enter the correct password")
return false;
Event.preventDefault();
}
return true;
}
</script>
Does anyone know if something...
Use a boolean and two if statements. Return the boolean at the end for true or false.
function validatePassword() {
const pw = document.getElementById("txtPassword").value;
const cpw = document.getElementById("txtCPassword").value;
let isValid = true;
if (pw.length < 8) {
alert('Password is not long enough. Minimum length is 8 characters.');
isValid = false;
}
if(pw !== cpw)) {
alert('Passwords do not match'.);
isValid = false;
}
return isValid;
}
Or have both messages in one alert using an array
function validatePassword() {
const pw = document.getElementById("txtPassword").value;
const cpw = document.getElementById("txtCPassword").value;
const errors = [];
if (pw.length < 8) {
errors.push('Password is not long enough. Minimum length is 8 characters.');
}
if(pw !== cpw)) {
errors.push('Passwords do not match.');
}
if (errors.length) {
alert(errors.join('\n'));
return false;
}
return true;
}
here is most basic version you can use this type of code.
function validatePassword(){
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
if((pw.length < 8))
{
alert("please enter the correct password")
return false;
} else if((cpw != pw)) {
alert("Passwords does not match")
} else {
alert("Password is correct!")
return true;
}
}
<form id="form">
<input type="text" id="txtPassword">
<input type="text" id="txtCPassword">
<input onclick="event.preventDefault();validatePassword()" type="submit" value="Submit">
</form>
This will do.
<script>
var pw= document.getElementById("txtPassword").value;
var cpw= document.getElementById("txtCPassword").value;
function validatePassword(){
if(pw.length < 8)
{
alert("Password need minimum 8 characters")
}
if(pw != cpw){
alert("Passwords does not match")
}
}
I don't think you need to show 2 alerts. When txtPassword is invalid, users have to retype both passwords whether passwords match or not. There is no point in showing "Passwords does not match" message in that case.
To know how to show 2 alerts, see my second code.
First, here is another solution:
const FORM = document.querySelector('#form');
const PSW = document.querySelector('#txtPassword');
const C_PSW = document.querySelector('#txtCPassword');
FORM.addEventListener('submit', event => {
event.preventDefault();
if (!validatePassword()) return;
console.log('Submitted');
})
function validatePassword() {
let pw = PSW.value;
let cpw = C_PSW.value;
if (pw.length < 8) {
alert('please enter the correct password');
return;
} else if (pw !== cpw) {
alert('Passwords does not match');
return;
}
return true;
}
<form action="" id="form">
<input type="password" id="txtPassword">
<input type="password" id="txtCPassword">
<input type="submit" value="Submit">
</form>
To show 2 alerts:
function validatePassword() {
let pw = PSW.value;
let cpw = C_PSW.value;
if (pw.length < 8) {
alert('please enter the correct password');
if (pw !== cpw) {
alert('Passwords does not match');
}
return;
} else if (pw !== cpw) {
alert('Passwords does not match');
return;
}
return true;
}
I want the form to not be submitted when the inputs are wrong. The error messages do appear but my form still gets submitted nonetheless. I cant seem to find the problem would appreciate the help thank you :)-----------------------------------------------------------------------------------------------------
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading" >First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
fname.style.color="red";
return false;
} else {
fname.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false)
{
errorC.innerHTML = "Wrong format";
mcode.style.color="red";
return false;
} else {
mcode.innerHTML = "";
}
return true; }
The problem seems to be these four lines of code:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
fname and mname are strings, therfore fname.style and mname.style both result in undefined. Obviously you can't set properties on undefined which is why you are getting an error.
//You are getting the value properties which are strings:
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
The error is stopping your code before you can return false, preventing the cancelation of the form submit.
The solution is to instead make two more variables storing the actual input elements:
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
Then change lines:
fname.style.color="red";
fname.innerHTML = "";
mname.style.color="red";
mname.innerHTML = "";
to:
finput.style.color="red";
finput.innerHTML = "";
minput.style.color="red";
minput.innerHTML = "";
Here is a working version:
<form action="/handleServer.php" method="get" onsubmit="return validateForm()">
<!-- starting with first name-->
<h4 class="heading">First name:</h4>
<input id="fname" type="text" name="fname" size="30">
<span id="errorName" class="error"></span>
<!-- module code -->
<h4 class="heading">Module code:</h4>
<input id="mcode" type="text" name="mcode" size="30">
<span id="errorCode" class="error"></span>
<input type="submit" value="Submit">
</form>
<script>
//input field using if-else statements
function validateForm() {
var finput = document.getElementById("fname");
var minput = document.getElementById("mname");
var fname = document.getElementById("fname").value;
var mcode = document.getElementById("mcode").value;
var errorN = document.getElementById("errorName");
var errorC = document.getElementById("errorCode");
//test for an empty input
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}
if (fname === '') {
errorN.innerHTML = "Please fill in the blank";
return false;
} else {
errorN.innerHTML = "";
}
if (mcode === '') {
errorC.innerHTML = "Please fill in the blank";
return false;
} else {
errorC.innerHTML = "";
}
//test for invalid format
if (/^[A-Z]\D{2,30}$/.test(fname) == false) //if its true, it will go to the second input
{
errorN.innerHTML = "One capital letter and no digits allowed";
finput.style.color = "red";
return false;
} else {
finput.innerHTML = "";
}
if (/^[a-z]{3}[1-9]\d{4}$/.test(mcode) == false) {
errorC.innerHTML = "Wrong format";
minput.style.color = "red";
return false;
} else {
minput.innerHTML = "";
}
return true;
}
</script>
Pass the event to the form validation function
onsubmit="return validateForm(e)"
Then prevent default submission using
e.preventDefault();
Your return statement should be inside a condition. Right now you're existing the condition and ending the function with a return true; regardless of what the conditional statements have already returned. So:
if (fname === '' && mcode === '') {
errorN.innerHTML = "Please fill in the blank";
errorC.innerHTML = "Please fill in the blank";
return false;
}else{
return true; // THIS IS WHERE YOU NEED TO RETURN TRUE
}
I see you're returning false in multiple if statements. You'll need to find a way to unify the conditions so that you have one return only for for either true or false.
I have created my code accordingly.
I recently changed the form action and now the form validation warnings are no longer applying on page load. For instance, if I click submit without entering data into any of the fields, I get 0 response and forwarded to the confirm.html page which should not be happening.
window.onload = init;
//creation of checkRegistration method
function checkRegistration() {
//definition of variables
//var checkev = 0;
var userName = document.getElementById('userName').value;
var password = document.getElementById('password').value;
var passwordVerify = document.getElementById('passwordVerify').value;
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var email = document.getElementById('email').value;
var phoneNumber = document.getElementById('phoneNumber').value;
var signUpNewsletter = document.getElementById('signUpNewsletter').value;
var userNameError = false,
passwordError = false,
passwordVerifyError = false,
firstNameError = false,
lastNameError = false,
emailError = false,
phoneNumberError = false;
// define logic checks
var alphaOnly = /^[A-Za-z]+$/;
var alphaNum = /^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i;
var phoneFormat = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
var atrate = email.indexOf("#");
var dot = email.lastIndexOf(".");
//clearning out warniings
document.getElementById('userNameWarning').innerHTML = "";
document.getElementById('passwordWarning').innerHTML = "";
document.getElementById('passwordVerifyWarning').innerHTML = "";
document.getElementById('firstNameWarning').innerHTML = "";
document.getElementById('lastNameWarning').innerHTML = "";
document.getElementById('emailWarning').innerHTML = "";
document.getElementById('phoneNumberWarning').innerHTML = "";
//validation of username, first checking to see if there is no value, then checking for alphanumeric condition, else the variable checkev is incremented
if (userName == "") {
//passes error requiring something to be entered
document.getElementById('userNameWarning').innerHTML = "A username is required.";
//moves cursor to this field if error occurs
//document.pageForm.userName.focus();
//document.pageForm.userName.select();
//checkev=0;
userNameError = true;
//ensures that username meets alphanumberic regex requirements
} else if (!userName.match(alphaNum)) {
document.getElementById('userNameWarning').innerHTML = "Username must contain at least one letter and one number, no special characters.";
userNameError = true;
//passes check with no error and increments checkev
//else {
// document.getElementById('userName').innerHTML = "";
//checkev++;
}
//validation of password, first checking to see if there is no value, then checking to make sure the password is at least 8 character in lenght, else the variable checkev is incremented
if (password == "") {
//passes error requiring something to be entered
document.getElementById('passwordWarning').innerHTML = "A password is required.";
//moves cursor to this field if error occurs
//document.pageForm.password.focus();
//document.pageForm.password.select();
//checkev = 0;
passwordError = true;
//check if password length is 8 or more characters
} else if (password.length <= 8) {
document.getElementById('passwordWarning').innerHTML = "A password of at least 8 characters is required.";
passwordError = true;
//else {
//document.getElementById('password').innerHTML = "";
//checkev++;
}
//validation of passwordVerify, first checking to see if there is no value, then checking to be sure that password verify matches password, inherently verifying that the password needs to be 8 characters in length, else the variable checkev is incremented
if (passwordVerify == "" ) {
document.getElementById('passwordVerifyWarning').innerHTML = "Please verify your password.";
//document.pageForm.passwordVerify.focus();
//document.pageForm.passwordVerify.select();
//checkev = 0;
passwordVerifyError = true;
} else if (password != passwordVerify) {
document.getElementById('passwordVerifyWarning').innerHTML = "Passwords do not match, password must be 8 characters.";
passwordVerifyError = true;
//else {
//document.getElementById('passwordVerify').innerHTML = "";
// checkev++;
}
//validation of first name, first checking to see if there is no value, then checking to see that the first name field is text only and no numerals, else the variable checkev is incremented
if (firstName == "") {
document.getElementById('firstNameWarning').innerHTML = "Your first name is required.";
//document.pageForm.firstName.focus();
//document.pageForm.firstName.select();
//checkev = 0;
firstNameError = true;
} else if (!(firstName.match(alphaOnly))) {
document.getElementById('firstNameWarning').innerHTML = "Please use only letters in this field.";
firstNameError = true;
//else {
//document.getElementById('firstName').innerHTML = "";
//checkev++;
}
//validation of last name, first checking to see if there is no value, then checking to see that the last name field is text only and no numerals, else the variable checkev is incremented
if (lastName == "") {
document.getElementById('lastNameWarning').innerHTML = "Your last name is required.";
//document.pageForm.lastName.focus();
//document.pageForm.lastName.select();
// checkev = 0;
lastNameError = true;
} else if (!(lastName.match(alphaOnly))) {
document.getElementById('lastNameWarning').innerHTML = "Please use only letters in this field.";
lastNameError = true;
//else {
// document.getElementById('lastName').innerHTML = "";
//checkev++;
}
//validation of email
if (email == "") {
document.getElementById('emailWarning').innerHTML = "Your email address is required.";
// document.pageForm.email.focus();
// document.pageForm.email.select();
//checkev = 0;
emailError = true;
} else if (atrate < 1 || dot < atrate + 2 || dot + 2 >= email.length) {
document.getElementById('emailWarning').innerHTML = "Your email input is not valid.";
emailError = true;
// else {
// document.getElementById('email').innerHTML = "";
//checkev++;
}
//validation of phone number, first checking to see if there is no value, then checking to see that the phonenumber should match the required phoneFormat, else the variable checkev is incremented
if (phoneNumber == "") {
document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required.";
//document.pageForm.phoneNumber.focus();
//document.pageForm.phoneNumber.select();
//checkev = 0;
phoneNumberError = true;
} else if (!(phoneNumber.match(phoneFormat))) {
document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required in (XXX) XXX-XXXX format.";
// else {
//document.getElementById('phoneNumber').innerHTML = "";
// checkev++;
phoneNumberError = true;
}
if (userNameError === true) {
document.getElementById('userName').focus();
return false;
} else if (passwordError === true) {
document.getElementById('password').focus();
return false;
} else if (passwordVerifyError === true) {
document.getElementById('passwordVerify').focus();
return false;
} else if (firstNameError === true) {
document.getElementById('firstName').focus();
return false;
} else if (lastNameError === true) {
document.getElementById('lastName').focus();
return false;
} else if (emailError === true) {
document.getElementById('email').focus();
return false;
} else if (phoneNumberError === true) {
document.getElementById('phoneNumber').focus();
return false;
}
//validation of sign up for newsletter, checking to see if there is nothing
}
<form id="pageForm">
<form action="/registration.html" onsubmit=checkRegistration() method="get">
<label for="userName">Username:</label><label2 id="userNameWarning"></label2>
<input type="text" name="userName" id="userName" placeholder="Enter your Username" />
<!--<span class="error" id="userName"></span><br><br>-->
<label for="Password">Password:
</label><label2 id="passwordWarning"></label2>
<input type="password" name="password" placeholder="Enter your Password" />
<!--<span class="error" id="password"></span><br><br>-->
<label for="passwordVerify">Verify your Password:
</label><label2 id="passwordVerifyWarning"></label2>
<input type="password" name="passwordVerify" placeholder="Enter in your Password again" />
<!--<span class="error" id="passwordVerify"></span><br><br>-->
<label for="firstName">First Name:
</label><label2 id="firstNameWarning"></label2>
<input type="text" name="firstName" placeholder="Enter your First Name" />
<!--<span class="error" id="firstName"></span><br><br>-->
<label for="hostName">Last Name:
</label><label2 id="lastNameWarning"></label2>
<input type="text" name="lastName" placeholder="Enter your Last Name" />
<!--<span class="error" id="lastName"></span><br><br>-->
<label for="email">Email:
</label><label2 id="emailWarning"></label2>
<input type="text" name="email" placeholder="Enter your Email Address" />
<!--<span class="error" id="email"></span><br><br>-->
<label for="phoneNumber">Phone Number:
</label><label2 id="phoneNumberWarning"></label2>
<input type="text" name="phoneNumber" placeholder="Enter your Phone Number" />
<!--<span class="error" id="phoneNumber"></span><br><br>-->
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" value="Yes" checked > Yes
<input type="radio" name="signUpNewsletter" value="No"> No
<!--<br><br><span class="error" id="signUpNewsletter"></span><br><br>-->
<!-- Creation of submit button-->
<input type="submit" value="Submit" formaction=confirm.html>
</form></form></body>
First, you need to remove window.onload = init; as it throws an error initially.
Second, your form tag is nested in another form tag which is completely unnecessary and prevents the form from triggering the onsubmit function which causes the error of submitted empty forms.
Lastly, your input elements don't actually have IDs, just names. So as Alon said in the comments your document.getElementById('element').value wont function correctly.
Try moving forward with the code snippet below as it corrects some of the main errors so you're actually hitting the validation conditions.
//creation of checkRegistration method
function checkRegistration() {
//definition of variables
//var checkev = 0;
var userName = document.getElementById('userName').value;
var password = document.getElementById('password').value;
var passwordVerify = document.getElementById('passwordVerify').value;
var firstName = document.getElementById('firstName').value;
var lastName = document.getElementById('lastName').value;
var email = document.getElementById('email').value;
var phoneNumber = document.getElementById('phoneNumber').value;
var signUpNewsletter = document.getElementById('signUpNewsletter').value;
var userNameError = false,
passwordError = false,
passwordVerifyError = false,
firstNameError = false,
lastNameError = false,
emailError = false,
phoneNumberError = false;
// define logic checks
var alphaOnly = /^[A-Za-z]+$/;
var alphaNum = /^(?:[0-9]+[a-z]|[a-z]+[0-9])[a-z0-9]*$/i;
var phoneFormat = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$/im;
var atrate = email.indexOf("#");
var dot = email.lastIndexOf(".");
//clearning out warniings
document.getElementById('userNameWarning').innerHTML = "";
document.getElementById('passwordWarning').innerHTML = "";
document.getElementById('passwordVerifyWarning').innerHTML = "";
document.getElementById('firstNameWarning').innerHTML = "";
document.getElementById('lastNameWarning').innerHTML = "";
document.getElementById('emailWarning').innerHTML = "";
document.getElementById('phoneNumberWarning').innerHTML = "";
//validation of username, first checking to see if there is no value, then checking for alphanumeric condition, else the variable checkev is incremented
if (userName == "") {
//passes error requiring something to be entered
document.getElementById('userNameWarning').innerHTML = "A username is required.";
//moves cursor to this field if error occurs
//document.pageForm.userName.focus();
//document.pageForm.userName.select();
//checkev=0;
userNameError = true;
//ensures that username meets alphanumberic regex requirements
} else if (!userName.match(alphaNum)) {
document.getElementById('userNameWarning').innerHTML = "Username must contain at least one letter and one number, no special characters.";
userNameError = true;
//passes check with no error and increments checkev
//else {
// document.getElementById('userName').innerHTML = "";
//checkev++;
}
//validation of password, first checking to see if there is no value, then checking to make sure the password is at least 8 character in lenght, else the variable checkev is incremented
if (password == "") {
//passes error requiring something to be entered
document.getElementById('passwordWarning').innerHTML = "A password is required.";
//moves cursor to this field if error occurs
//document.pageForm.password.focus();
//document.pageForm.password.select();
//checkev = 0;
passwordError = true;
//check if password length is 8 or more characters
} else if (password.length <= 8) {
document.getElementById('passwordWarning').innerHTML = "A password of at least 8 characters is required.";
passwordError = true;
//else {
//document.getElementById('password').innerHTML = "";
//checkev++;
}
//validation of passwordVerify, first checking to see if there is no value, then checking to be sure that password verify matches password, inherently verifying that the password needs to be 8 characters in length, else the variable checkev is incremented
if (passwordVerify == "" ) {
document.getElementById('passwordVerifyWarning').innerHTML = "Please verify your password.";
//document.pageForm.passwordVerify.focus();
//document.pageForm.passwordVerify.select();
//checkev = 0;
passwordVerifyError = true;
} else if (password != passwordVerify) {
document.getElementById('passwordVerifyWarning').innerHTML = "Passwords do not match, password must be 8 characters.";
passwordVerifyError = true;
//else {
//document.getElementById('passwordVerify').innerHTML = "";
// checkev++;
}
//validation of first name, first checking to see if there is no value, then checking to see that the first name field is text only and no numerals, else the variable checkev is incremented
if (firstName == "") {
document.getElementById('firstNameWarning').innerHTML = "Your first name is required.";
//document.pageForm.firstName.focus();
//document.pageForm.firstName.select();
//checkev = 0;
firstNameError = true;
} else if (!(firstName.match(alphaOnly))) {
document.getElementById('firstNameWarning').innerHTML = "Please use only letters in this field.";
firstNameError = true;
//else {
//document.getElementById('firstName').innerHTML = "";
//checkev++;
}
//validation of last name, first checking to see if there is no value, then checking to see that the last name field is text only and no numerals, else the variable checkev is incremented
if (lastName == "") {
document.getElementById('lastNameWarning').innerHTML = "Your last name is required.";
//document.pageForm.lastName.focus();
//document.pageForm.lastName.select();
// checkev = 0;
lastNameError = true;
} else if (!(lastName.match(alphaOnly))) {
document.getElementById('lastNameWarning').innerHTML = "Please use only letters in this field.";
lastNameError = true;
//else {
// document.getElementById('lastName').innerHTML = "";
//checkev++;
}
//validation of email
if (email == "") {
document.getElementById('emailWarning').innerHTML = "Your email address is required.";
// document.pageForm.email.focus();
// document.pageForm.email.select();
//checkev = 0;
emailError = true;
} else if (atrate < 1 || dot < atrate + 2 || dot + 2 >= email.length) {
document.getElementById('emailWarning').innerHTML = "Your email input is not valid.";
emailError = true;
// else {
// document.getElementById('email').innerHTML = "";
//checkev++;
}
//validation of phone number, first checking to see if there is no value, then checking to see that the phonenumber should match the required phoneFormat, else the variable checkev is incremented
if (phoneNumber == "") {
document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required.";
//document.pageForm.phoneNumber.focus();
//document.pageForm.phoneNumber.select();
//checkev = 0;
phoneNumberError = true;
} else if (!(phoneNumber.match(phoneFormat))) {
document.getElementById('phoneNumberWarning').innerHTML = "Your phone number is required in (XXX) XXX-XXXX format.";
// else {
//document.getElementById('phoneNumber').innerHTML = "";
// checkev++;
phoneNumberError = true;
}
if (userNameError === true) {
document.getElementById('userName').focus();
return false;
} else if (passwordError === true) {
document.getElementById('password').focus();
return false;
} else if (passwordVerifyError === true) {
document.getElementById('passwordVerify').focus();
return false;
} else if (firstNameError === true) {
document.getElementById('firstName').focus();
return false;
} else if (lastNameError === true) {
document.getElementById('lastName').focus();
return false;
} else if (emailError === true) {
document.getElementById('email').focus();
return false;
} else if (phoneNumberError === true) {
document.getElementById('phoneNumber').focus();
return false;
}
//validation of sign up for newsletter, checking to see if there is nothing
}
<!DOCTYPE html>
<html lang="en">
<meta charset="utf8">
<title>tester</title>
<body class="container">
<form id="pageForm" onsubmit="return checkRegistration()" action="/registration.html" method="get">
<label for="userName">Username:</label><label2 id="userNameWarning"></label2>
<input type="text" name="userName" id="userName" placeholder="Enter your Username" />
<!--<span class="error" id="userName"></span><br><br>-->
<label for="Password">Password:
</label><label2 id="passwordWarning"></label2>
<input type="password" name="password" id="password" placeholder="Enter your Password" />
<!--<span class="error" id="password"></span><br><br>-->
<label for="passwordVerify">Verify your Password:
</label><label2 id="passwordVerifyWarning"></label2>
<input type="password" name="passwordVerify" id="passwordVerify" placeholder="Enter in your Password again" />
<!--<span class="error" id="passwordVerify"></span><br><br>-->
<label for="firstName">First Name:
</label><label2 id="firstNameWarning"></label2>
<input type="text" name="firstName" id = "firstName" placeholder="Enter your First Name" />
<!--<span class="error" id="firstName"></span><br><br>-->
<label for="hostName">Last Name:
</label><label2 id="lastNameWarning"></label2>
<input type="text" name="lastName" id= "lastName" placeholder="Enter your Last Name" />
<!--<span class="error" id="lastName"></span><br><br>-->
<label for="email">Email:
</label><label2 id="emailWarning"></label2>
<input type="text" name="email" id="email" placeholder="Enter your Email Address" />
<!--<span class="error" id="email"></span><br><br>-->
<label for="phoneNumber">Phone Number:
</label><label2 id="phoneNumberWarning"></label2>
<input type="text" name="phoneNumber" id = "phoneNumber" placeholder="Enter your Phone Number" />
<!--<span class="error" id="phoneNumber"></span><br><br>-->
<label for="signUpNewsletter">Sign up for newsletter:
</label>
<input type="radio" name="signUpNewsletter" value="Yes" checked > Yes
<input type="radio" name="signUpNewsletter" id="signUpNewsletter" value="No"> No
<!--<br><br><span class="error" id="signUpNewsletter"></span><br><br>-->
<!-- Creation of submit button-->
<input type="submit" value="Submit" formaction=confirm.html>
</form></body>
<script src="app.js"></script>
It seems that my original question was closed out. I was able to complete most of the form validation requirement for my Pizza form. However now I'm just stuck at the phone number validation and format.
I need assistants for form validation for my phone number.
The phone number must be Numbers only with Dash for example 222-222-2222 and anything else besides that format or an empty field should cause an alert when I hit my submit button and doe snot allow the form to be submitted unless it is correct
Please review my code for document.PizzaForm.phone.value code for my pizza form I'm not sure how to edit the code to achieve my requirement.
<html>
<head>
<title>Hello and JavaScript</title>
<script>
function doClear()
{
document.PizzaForm.customer.value = "";
document.PizzaForm.address.value = "";
document.PizzaForm.city.value = "";
document.PizzaForm.state.value = "";
document.PizzaForm.zip.value = "";
document.PizzaForm.phone.value = "";
document.PizzaForm.email.value = "";
document.PizzaForm.sizes[0].checked = false;
document.PizzaForm.sizes[1].checked = false;
document.PizzaForm.sizes[2].checked = false;
document.PizzaForm.sizes[3].checked = false;
document.PizzaForm.toppings[0].checked = false;
document.PizzaForm.toppings[1].checked = false;
document.PizzaForm.toppings[2].checked = false;
document.PizzaForm.toppings[3].checked = false;
document.PizzaForm.toppings[4].checked = false;
document.PizzaForm.toppings[5].checked = false;
document.PizzaForm.toppings[6].checked = false;
document.PizzaForm.toppings[7].checked = false;
document.PizzaForm.toppings[8].checked = false;
return;
}
function doSubmit()
{
if (validateText()==false)
{
alert("Required data missing in Step 1");
}
if (validateRadio()==false)
{
alert("Required data missing in Step 2");
}
if(validateTops()==false)
{
alert("Required data missing in Step 3");
}
var OrderWindow
OrderWindow = window.open("","","status,height=500,width=500");
OrderWindow.focus();
with (OrderWindow.document)
{
write("<h1><center>Customer Order Summary</center></h1><p>")
write("Name:" + document.PizzaForm.customer.value + "<br>")
write("Address:" + document.PizzaForm.address.value + "<br>")
write("City:" + document.PizzaForm.city.value + "<br>")
write("State:" + document.PizzaForm.state.value + "<br>")
write("Zip Code:" + document.PizzaForm.zip.value + "<br>")
write("Phone Number:" + document.PizzaForm.phone.value + "<br>")
write("E-Mail:" + document.PizzaForm.email.value + "<br>")
write("Pizza Size:" + validateRadio() + "<br>")
write("Pizza Toppings:" + validateTops() + "<br>")
write("<h3><center>Thank You for your Order.</center></h3><p>")
}
return;
}
function validateText()
{
if (document.PizzaForm.customer.value == "")
{
alert("Please provide your name");
document.PizzaForm.customer.focus();
}
if (document.PizzaForm.address.value == "")
{
alert("Please provide your address.");
document.PizzaForm.address.focus();
}
if (document.PizzaForm.city.value == "")
{
alert("Please provide your City.");
}
if (document.PizzaForm.state.value == "")
{
alert("Please provide your State.");
}
if (document.PizzaForm.zip.value == "" ||
isNaN( document.PizzaForm.zip.value ) ||
document.PizzaForm.zip.value.length != 5 )
{
alert("Please provide your Zip code.");
document.PizzaForm.zip.focus() ;
}
if (document.PizzaForm.phone.value == "" ||
isNaN( document.PizzaForm.phone.value ) ||
document.PizzaForm.phone.value.length != 10 )
{
alert("Please provide your phone number.");
document.PizzaForm.phone.focus() ;
}
var emailID = document.PizzaForm.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct Email.")
document.myForm.Email.focus() ;
}
return (true);
}
function validateRadio()
{
if (document.PizzaForm.sizes[0].checked) true;
if (document.PizzaForm.sizes[1].checked) true;
if (document.PizzaForm.sizes[2].checked) true;
if (document.PizzaForm.sizes[3].checked) true;
return false;
}
function validateTops()
{
var sizes = document.PizzaForm.toppings;
var alert = ""
if (PizzaForm.toppings[0].checked) alert = "Pepperoni, " + alert;
if (PizzaForm.toppings[1].checked) alert = "Canadian Bacon, " + alert;
if (PizzaForm.toppings[2].checked) alert = "Sausage, " + alert;
if (PizzaForm.toppings[3].checked) alert = "Mushrooms, " + alert;
if (PizzaForm.toppings[4].checked) alert = "Pineapple, " + alert;
if (PizzaForm.toppings[5].checked) alert = "Black Olives, " + alert;
if (PizzaForm.toppings[6].checked) alert = "Extra Cheese, " + alert;
if (PizzaForm.toppings[7].checked) alert = "Plain, " + alert;
return alert;
}
</script>
</head>
<body>
<form Name ="PizzaForm">
<h1> The JavaScrpt Pizza Parlor</h>
<p>
<h4> Step 1: Enter your name, address, phone number, and email:</h4>
<font face="Courier New">
Name: <Input name="customer" size="50" type="text"><br>
Address: <Input name="address" size="50" type="text"><br>
City: <Input name="city" size="15"type="text">
State:<Input name="state" size="2"type="text"><br>
Zip: <Input name="zip" size="5"type="text"> <br>
Phone: <Input name="phone" size="50"type="text"><br>
Email: <Input name="email" size="31"type="text"><br>
</ font>
</ p>
<p>
<h4> Step 2: Select the size of pizza you want:</h4>
<font face="Courier New">
<input name="sizes" type="radio">Small
<input name="sizes" type="radio">Medium
<input name="sizes" type="radio">Large
<input name="sizes" type="radio">Jumbo<br>
</font>
</ p>
<p>
<h4> Step 3: Select the pizza toppings you want:</h4>
<font face="Courier New">
<input name="toppings" type="checkbox">Pepperoni
<input name="toppings" type="checkbox">Canadian Bacon
<input name="toppings" type="checkbox">Sausage<br>
<input name="toppings" type="checkbox">Mushrooms
<input name="toppings" type="checkbox">Pineapple
<input name="toppings" type="checkbox">Black Olives<br>
<input name="toppings" type="checkbox">Green Peppers
<input name="toppings" type="checkbox">Extra Cheese
<input name="toppings" type="checkbox">Plain
</ font>
</ p>
<input type="button" value="Submit Order" onClick="doSubmit()">
<input type="button" value="Clear Entries" onClick="doClear()">
</form>
</body>
</html>
The phone number must be Numbers only with Dash for example 222-222-2222
You can use a regex to check your phone number. This will match exactly 3 digits, a dash, 3 digits, a dash, and a final 4 digits.
var phone = "222-222-2222";
if (!/^\d{3}-\d{3}-\d{4}$/.test(phone)) {
console.log("bad number");
} else {
console.log("good number");
}
Then change your code to this:
if (!/^\d{3}-\d{3}-\d{4}$/.test(document.PizzaForm.phone.value)) {
alert("Please provide a correct phone number.");
document.PizzaForm.phone.focus();
}
If you are more flexible on your phone number format, for example allowing brackets around the area code, then please see below for more solutions:
http://www.regexplanet.com/advanced/javascript/index.html
https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9781449327453/ch04s02.html
What about an alert for a blank field that says please enter phone number?
// This will treat empty strings, spaces and tabs as "empty"
function isEmpty(str){
return !str.replace(/^\s+/g, '').length;
}
if (isEmpty(document.PizzaForm.phone.value)) {
alert("Please enter a phone number.");
document.PizzaForm.phone.focus();
} else if (!/^\d{3}-\d{3}-\d{4}$/.test(document.PizzaForm.phone.value)) {
alert("Please provide a correct phone number.");
document.PizzaForm.phone.focus();
}
Assuming that's the pattern you want (xxx-xxx-xxxx), including the dashes, this works:
function validatePhone(ipt){
if(ipt.search('[0-9]{3}-[0-9]{3}-[0-9]{4}') === 0 && ipt.length === 12){
return true;
} else {
return false;
}
}
console.log(validatePhone('123-456-7890'));
console.log(validatePhone('abc-def-ghij'));
console.log(validatePhone('123-456-789'));
Of course, leave out the testing code.
I actually recommend letting them use dashes, slashes, or whatever, then just parsing them out:
window.verify = function() {
var phone = document.getElementById("phone").value.split("");
var verified = "";
for (var char in phone)
{
verified += parseInt(phone[char]) >= 0 ? phone[char] : "";
}
var len = verified.length;
if (len != 7 && len != 10)
{
alert("Invalid number of digits!");
}
else
{ // then format the resulting number as you see fit
var finalNum = "";
if (len == 10)
{
finalNum += verified.substring(0,3) + "-"
verified = verified.substring(3);
}
finalNum += verified.substring(0,3) + "-";
verified = verified.substring(3);
finalNum += verified;
alert(""+finalNum);
}
}
<input type="text" id="phone" />
<br>
<br>
<button type="button" onclick="verify()">Validate Phone</button>
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>