I am trying to validate telephone number in this format : (xxx) xxx-xxxx.
For that I have used regular expression but it doesn't validate when I enter incorrect format and click on submit it doesn't show any error. Can anyone help me to identify an issue?
code:
<!DOCTYPE html>
<html>
<head>
<title>NumerValidation</title>
</head>
<body>
<form name="myform" id="myform" action="" onsubmit="return validateForm()" method="post">
<table cellspacing="2" cellpadding="2" border="0">
<tr>
<td align="right">Telephone number</td>
<td><input type="text" name="phone" size="28" placeholder="(555) 555-5555"/></td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /> </td>
</tr>
</table>
</form>
<script>
function validateForm() {
var phone = document.myform.phone;
var regPhone = /^\(?[(]?[0-9]{3}[)]?[-\s]?[0-9]{3}[-]?[0-9]{4}$/im;
//var phone = /^\(?([0-9]{3})\)?[-]?([0-9]{3})[-]?([0-9]{4})$/;
if(phone.value.match(regPhone))
{
return true;
}
else
{
window.alert("Please enter Telephone number in (xxx) xxx-xxxx format.");
return false;
}
}
</script>
</body>
</html>
use this regular expression
^\(\d{3}\)\s{0,}\d{3}\s{0,}-\s{0,}\d{4}$
it matches
(111)111 - 1111
(111) 111 - 1111
(111) 111- 1111
(111) 111- 1111
(111) 111-1111
(111) 111 - 1111
incase the user adds spaces at the beginning or end of the phone number, you have to trim it with
value = value.trimLeft();
value = value.trimRight();
if you don't trim white spaces at the beginning and end of the input, the regexp will fail even if the user inputs valid number
Related
I'm working on a form validation project that requires multiple input fields connected to a single submit button. I more or less figured the button out, but I'm having an issue getting the functions themselves to work properly. I currently only have three of the eleven fields typed up for testing, but what the page should do is let you know which fields are invalid when there is nothing filled out in them (changing text/background colors, message below, etc).
The issue I'm having is that when the requirements for the first field (Gift Card Number) are met, it acts as though there isn't any issues anywhere, regardless of whether or not the other input fields (First name, Last name) have been filled. They all seem to function correctly if none of the fields are filled, but my concern is that the functions seem to be firing in order and first one to work negates all the ones after (for example, Gift Card prevents First and Last, First prevents Last, etc).
Any ideas where I've gone wrong here? I'll include my html and my javascript. (Yes, I know the html is a bit ugly, I plan to move the material over to a div table later, just trying to get it to function for now) Any help appreciated as always!
HTML
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<table>
<tbody>
<tr id="rONE">
<td><h4>Gift Card Amount</h4>
<form name="giftForm" onsubmit="return validateGiftCard()" method="post" id="GiftCardForm">
<input type="text" name="giftInput">
<h5 id="giftMessage"></h5></td>
<input type="submit" value="Submit" style="display:none" />
<td></td>
</tr>
</form>
<tr id="rTWO-1">
<td><h4>Recipient's name</h4>
</td>
<td> </td>
</tr>
<tr id="rTWO-2">
<td>
<form name="firstForm" onsubmit="return validateRecipient()" method="post">
<input type="text" name="firstInput">
<br>
<h4>First</h4>
</form>
</td>
<td><form name="lastForm" method="post">
<input type="text" name="lastInput">
<br>
<h4>Last</h4></td>
</form>
</tr>
<tr>
<td><h5 id="recipientMessage"></h5></td></td>
<td> </td>
</tr>
</tbody>
</table>
<button type="submit" id="btn" form="GiftCardForm" value="Submit">Submit</button>
</body>
<footer>
<script src="Form Validation.js"></script>
</footer>
</html>
Javascript
document.getElementById('btn').addEventListener('click', function(){
validateGiftCard();
validateRecipient();
});
function validateGiftCard() {
valid = true;
if ( document.giftForm.giftInput.value == "" )
{
giftMessage.innerHTML = "This field is required";
document.getElementById("rONE").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
function validateRecipient() {
valid = true;
if ( document.firstForm.firstInput.value == "" )
{
recipientMessage.innerHTML = "This field is required";
document.getElementById("rTWO-1").style.backgroundColor="#fff7f7"
document.getElementById("rTWO-2").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
document.getElementById('btn').addEventListener('click', function(e) {
var v1 = validateGiftCard();
var v2 = validateRecipient();
console.log(v1, v2);
if (!v1 || !v2)
e.preventDefault();
});
function validateGiftCard() {
valid = true;
if (document.giftForm.giftInput.value == "") {
giftMessage.innerHTML = "This field is required";
document.getElementById("rONE").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
function validateRecipient() {
valid = true;
if (document.firstForm.firstInput.value == "") {
recipientMessage.innerHTML = "This field is required";
document.getElementById("rTWO-1").style.backgroundColor = "#fff7f7"
document.getElementById("rTWO-2").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
<table>
<tbody>
<tr id="rONE">
<td>
<h4>Gift Card Amount</h4>
<form name="giftForm" onsubmit="return validateGiftCard()" method="post" id="GiftCardForm">
<input type="text" name="giftInput">
<h5 id="giftMessage"></h5>
</form>
</td>
<input type="submit" value="Submit" style="display:none" />
<td></td>
</tr>
<tr id="rTWO-1">
<td>
<h4>Recipient's name</h4>
</td>
<td> </td>
</tr>
<tr id="rTWO-2">
<td>
<form name="firstForm" onsubmit="return validateRecipient()" method="post">
<input type="text" name="firstInput">
<br>
<h4>First</h4>
</form>
</td>
<td>
<form name="lastForm" method="post">
<input type="text" name="lastInput">
<br>
<h4>Last</h4>
</form>
</td>
</tr>
<tr>
<td>
<h5 id="recipientMessage"></h5>
</td>
<td> </td>
</tr>
</tbody>
</table>
<button type="submit" id="btn" form="GiftCardForm" value="Submit">Submit</button>
I am very new to html and javascript; I've only been coding a few weeks. I'm trying to create a registration form with validation and am having an issue with this assignment. I was getting the error in the title (left-hand side...) but now my validation function isn't working and I cannot see why.
This is my assignment:
The following are your data validation rules:
Username/Password: Required and has to be at least 8 characters.
First Name/Last Name: Required. No other requirements.
Email: Required.
Phone Number: Optional. However, if user enters a phone number, you must check to make sure that it is in XXX-XXX-XXXX format, where X
are all numbers.
When user clicks on the submit button, your validation logic will run
and display error messages on the screen if there are data issues. If
there are no data issues, you can just use “alert” to print a success
message. Include reset button to clear all form fields and errors.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Registration Form</title>
<link rel = "stylesheet" type="text/css" href = "regStyles.css"/>
<script language="JavaScript">
function validateForm()
{
var userName = document.getElementById('userName').value;
var passWord = document.getElementById('passWord').value;
var lastName = document.getElementById('lastName').value;
var dateBirth = document.getElementById('dateBirth').value;
var email = document.getElementById('email').value;
if (userName == "" || passWord =="" || firstName == "" || lastName == "" || dateBirth == "" || email == "")
{
document.getElementById("error").innerHTML = "Only phone is optional, all other fields are required";
return false;
}
else if (userName.length<8)
{
document.getElementById("error").innerHTML = "Username must be at least 8 characters.";
}
else if (passWord.length<8)
{
document.getElementById("error").innerHTML = "Password must be at least 8 characters.";
}
else
{
return true;
}
}
</script>
</head>
<body>
<form name = "registration" id = "registration" action="submission.html" method="post" onsubmit="return validateForm();">
<h1>Registration</h1>
<span id="error" style="color:red;"></span>
<table>
<tr>
<td>Username:</td>
<td><input type="text" id="userName" placeholder="JaneDoe123"> (At least 8 characters)
</tr>
<tr>
<td>Password:</td>
<td><input type="password" id="passWord" placeholder="********"> (At least 8 characters)
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" id="firstName" placeholder="Jane"></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type="text" id="lastName" placeholder="Doe"></td>
</tr>
<tr>
<td>Date of Birth:</td>
<td><input type="date" name="dateBirth"></td>
</tr>
<tr>
<td>Email:</td>
<td><input type="email" id="email" class="form-control" placeholder="jane.doe#email.com"></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><input type="tel" id="phoneNumber" name="phone" placeholder="502-555-1234"
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}"/>
<span class="validity"></span> (optional)</td>
</tr>
</table>
<input type="submit" value="Submit"></button>
<input type="reset">
</form>
</body>
</html>
I have an HTML form with some fields and a javascript validation that checks them, my problem is that js doesn't return anything, and although the fields are filled not propertly the submit sends.
Here an example of my code:
HTML
<form method="post" action="action.php" onsubmit="return validate_form();">
<table>
<tr>
<td>
<label class="standard_text">
E-mail
</label>
</td>
<td><input class="textarea" required type="email" name="mail" id="mail" placeholder="E-mail"></label></td>
<td><div class="check_icon icon_yes" style="display:none" id="mail_ok_icon"></div></td>
<td><div class="check_icon icon_no" style="display:none" id="mail_no_icon"></div></label></td>
<td><div class="check_message" style="display:none" id="mail_message"><label class="important_text">The email format is not correct!</label></div></td>
</tr>
</table>
<input class="button_submit" type="submit" name="send_form" value="Register"/>
</form>
Javascript
function validate_form(){
//email var
var mail = document.getElementById("mail").value;
var mail_ok_icon = document.getElementById("mail_ok_icon");
var mail_no_icon = document.getElementById("mail_no_icon");
var mail_message = document.getElementById("mail_message");
//email format check
if ((/(.+)#(.+){2,}\.(.+){2,}/.test(mail)) || mail=="" || mail==null) {
mail_no_icon.style.display="block";
mail_message.style.display="block";
return(false);
} else {
mail_ok_icon.style.display="block";
}
}
So I'm trying to display elements depending on the javascript checking and also trying to don't let the user send the information if the checking of all the fields are not correct.
What am I missing?
Thanks
I got it working with the following code -:
In the original code the email input had required and type="email" which never called the javascript code in the first instance.
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<form method="post" action="action.php" onsubmit="return validate_form();">
<table>
<tr>
<td>
<label class="standard_text">
E-mail
</label>
</td>
<td><input class="textarea" name="mail" id="mail" placeholder="E-mail"></label></td>
<td><div class="check_icon icon_yes" style="display:none" id="mail_ok_icon"></div></td>
<td><div class="check_icon icon_no" style="display:none" id="mail_no_icon"></div></label></td>
<td><div class="check_message" style="display:none" id="mail_message"><label class="important_text">The email format is not correct!</label></div></td>
</tr>
</table>
<input class="button_submit" type="submit" name="send_form" value="Register"/>
</form>
</body>
</html>
Now here is the js code -:
function validate_form() {
//email var
var mail = document.getElementById("mail").value;
var mail_ok_icon = document.getElementById("mail_ok_icon");
var mail_no_icon = document.getElementById("mail_no_icon");
var mail_message = document.getElementById("mail_message");
//email format check
if (!(/(.+)#(.+){2,}\.(.+){2,}/.test(mail)) || mail=="" || mail==null) {
mail_no_icon.style.display="block";
mail_message.style.display="block";
console.log('hi');
return false;
} else {
mail_ok_icon.style.display="block";
return true;
}
}
I am currently using html to code a 'form entry'. I am also using a JavaScript validation, to validate the input in of the form. So far, i have the 'name', 'subject' and 'Examination number'. However my validation does not work for my Examination number. for examination number, i want the validation to make sure that the input is only 4 digits, hence i added 'maxlength="4"'. If someone could please help me with this validation to firstly validate the examination number and ensure that the input is four digits, it would be very helpful, thanks
here is my code:
<head>
<title>Exam Entry</title>
<script language="javascript" type="text/javascript">
function validateForm(e) {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.Examination_number.value=="4") {
msg+="You must enter your Examination number \n";
document.ExamEntry.Examination_number.focus();
document.getElementById('Examination_number').style.color="red";
result = false;
}
if (msg != "") {
alert(msg);
}
return result;
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html" onsubmit="return validateForm();">
<table width="60%" border="0">
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<td id="Examination_number">Examination number</td>
<td><input type="text" maxlength="4" name="Examination_number" /></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
it's not .value == "4" it's .value.length == 4
You can actually use html5 for this, no javascript required!
Along with the maxlength attribute, include this attribute:
pattern="\d{4}"
the "pattern" attribute allows you to specify a regex pattern for validating the input.
\d is regex meaning "digits". {4} is regex meaning repeat exactly 4 times.
The maxlength attribute is actually redundant now, and can be removed since the regex will limit the length of the input on its own.
So overall, your element can look like:
<input type="text" pattern="\d{4}" name="Examination_number" />
Also just one note: It's also important to keep in mind that client side validation is not equivalent to server-side validation. Anyone with basic webdev knowledge will still be able to post invalid Examination_Number values to your server. Your server must be able to validate these values as well.
Use regex... var regex = /^\d{4}$/;
And of course, sorry, you can do it matching the regex... if (regex.test(examinationnumber)) then good..
You could also check the value with isNaN to be sure of getting numbers, like:
if (!isNaN(examinationnumber)) then good..
To make them alltogether:
var regex = /^\d{4}$/;
if (document.ExamEntry.Examination_number.value == "") {
msg+="You must enter your examination number";
result = false;
} else if (isNaN(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should only contain digits";
result = false;
} else if (!regex.test(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should contain exactly 4 digits";
result = false;
}
I am currently using html to code a 'form entry'. I am also using a JavaScript validation, to validate the input in of the form. At the moment, i have 'name', 'subject' and 'examination number', each working and having functional validations. For the 'qualification' fields, I have radio buttons where the user has to click-select their qualification. I have the validation in place, but unfortunately I cant get the field to be highlighted in red and display the error message when the form is submitted and the 'qualification' has been left blank. everything works apart from the qualification field. It would be great if someone could fix the validation of the 'qualification' so that when the field is left emty, the text will be highlighted and the error message will be included. thanks
here is my code:
<html>
<head>
<title>Exam Entry</title>
<script language="javascript" type="text/javascript">
function qualinform(qualname) {
alert(qualname + " was selected as your qualification.");
}
function validateForm(e) {
var result = true;
var msg="";
if (document.ExamEntry.name.value=="") {
msg+="You must enter your name \n";
document.ExamEntry.name.focus();
document.getElementById('name').style.color="red";
result = false;
}
if (document.ExamEntry.subject.value=="") {
msg+="You must enter the subject \n";
document.ExamEntry.subject.focus();
document.getElementById('subject').style.color="red";
result = false;
}
if (document.ExamEntry.group1.value=="") {
msg+="You must choose a qualification\n";
document.ExamEntry.group1.focus();
document.getElementById('radioqual').style.color="red";
result = false;
}
var regex = /^\d{4}$/;
if (document.ExamEntry.Examination_number.value == "") {
msg+="You must enter your examination number";
document.getElementById('Examination_number').style.color="red";
result = false;
} else if (isNaN(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should only contain digits";
document.getElementById('Examination_number').style.color="red";
result = false;
} else if (!regex.test(document.ExamEntry.Examination_number.value)) {
msg+="Examination number should contain exactly 4 digits";
document.getElementById('Examination_number').style.color="red";
result = false;
}
if (msg != "") {
alert(msg);
}
return result;
}
</script>
</head>
<body>
<h1>Exam Entry Form</h1>
<form name="ExamEntry" method="post" action="success.html" onsubmit="return validateForm();">
<table width=”50%” border=”0”>
<tr>
<td id="name">Name</td>
<td><input type="text" name="name" /></td>
</tr>
<tr>
<td id="subject">Subject</td>
<td><input type="text" name="subject" /></td>
</tr>
<td id="Examination_number">Examination number</td>
<td><input type="text" maxlength="4" name="Examination_number" /></td>
</tr>
<tr>
<td id="qualification">Choose your qualification</td>
<tr>
<td id="radioqual">
<input onclick="qualinform('GCSE');" type="radio" name="group1" value="GCSE">GCSE<br>
<input onclick="qualinform('AS');" type="radio" name="group1" value="AS">AS<br>
<input onclick="qualinform('A2');" type="radio" name="group1" value="A2">A2<br>
</td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Submit" /></td>
<td><input type="reset" name="Reset" value="Reset" /></td>
</tr>
</table>
</form>
</body>
</html>
the return value of the group1 radio buttons when none are selected is undefined, not "" as you expected, so you need to change the condition in the if statement
if (document.ExamEntry.group1.value==undefined)