I'm trying to use javascript regular expressions for my email input area. I've tried each of the following:
/^\S+#\S+$/
/\S+#\S+\.\S+/
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/
Neither of them work, and every other input field works fine. Here is my Javascript and html:
function checkForm(){
var isValid = true;
var name = document.forms['contact']['name'].value;
var email = document.forms['contact']['email'].value;
var emailpattern = /^\S+#\S+$/;
var subject = document.forms["contact"]["subject"].value;
var textarea = document.forms["contact"]["textarea"].value;
if(name == ""){
document.getElementById('nameMessage').innerHTML = "please enter a name";
isValid = false;
} else {
document.getElementById('nameMessage').style.display = "none";
}
if(!emailpattern.test(emailMessage)){
document.getElementById('emailMessage').innerHTML = "please enter a valid email";
isValid = false;
}
else {
document.getElementById('emailMessage').style.display = "none";
}
<form action="thankyou.html" id="contactId"name="contact" onsubmit="return checkForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<p id="nameMessage"></p>
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<p id="emailMessage"></p>
<div><button type="submit" id="submit">Submit</button></div>
You are using emailMessage wrong variable to test regex use email
and also you have to return false if any validation fails to prevent form from submitting.
function checkForm(){
var isValid = true;
var name = document.forms['contact']['name'].value;
var email = document.forms['contact']['email'].value;
var emailpattern = /^\S+#\S+$/;
if(name == ""){
document.getElementById('nameMessage').innerHTML = "please enter a name";
isValid = false;
return false;
} else {
document.getElementById('nameMessage').style.display = "none";
}
if(!emailpattern.test(emailMessage)){
document.getElementById('emailMessage').innerHTML = "please enter a valid email";
isValid = false;
return false;
}
else {
document.getElementById('emailMessage').style.display = "none";
}
}
<form action="thankyou.html" id="contactId"name="contact" onsubmit="return checkForm()">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<p id="nameMessage"></p>
<label for="email">Email:</label>
<input type="text" id="email" name="email">
<p id="emailMessage"></p>
<div><button type="submit" id="submit">Submit</button></div>
</form>
Related
Okay, I'm trying to get a contact form to work and it is, sort of. The data is passing through, but I can't get the jQuery to work. If I type in two different email addresses it doesn't catch it. Here is the relevant code I used:
HTML
<aside>
<form action="sendmail.php" method="post" name="contact_form" id="contact_form">
<fieldset>
<legend>sign up now!</legend><br>
<p>Sign up for my email list and get a free mini coloring book!</p><br>
<img src="Images/minicoloirngbook.jpg" alt="mini coloring book"><br>
<label for="name"> Name:</label>
<input type="text"name="name" id="name" required><span>*</span><br>
<label for="email">Email Address:</label>
<input type="email" name="email" id="email" required><span>*</span><br>
<label for="verify">Verify Email:</label>
<input type="email" name="verify" id="verify" required> <span>*</span><br>
<div id="buttons">
<input type="submit" id="submit" value="Sign Up">
</div>
</fieldset>
</form>
</aside>
and here is the Javascript:
$("#contact_form").submit(event => {
let isValid = true;
// validate the first name entry
const name = $("#name").val().trim();
if (name == "") {
$("#name").next().text("This field is required.");
isValid = false;
} else {
$("#name").next().text("");
}
$("#name").val(name);
// validate the email entry with a regular expression
const emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#email").val().trim();
if (email == "") {
$("#email").next().text("This field is required.");
isValid = false;
} else if ( !emailPattern.test(email) ) {
$("#email").next().text("Must be a valid email address.");
isValid = false;
} else {
$("#email").next().text("");
}
$("#email").val(email);
// validate the verify entry
const verify = $("#verify").val().trim();
if (verify == "") {
$("#verify").next().text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#verify").next().text("Must match first email entry.");
isValid = false;
} else {
$("#verify").next().text("");
}
$("#verify").val(verify);
// prevent the submission of the form if any entries are invalid
if (isValid == false) {
event.preventDefault();
}
}),
I think that the answer is probably something really simple that I can't see and would appreciate your help in figuring it out.
This should do it. Here is the jsfiddle if you like to play with the code: https://jsfiddle.net/bogatyr77/xk6ez3aq/7/
$("form").submit(function(e) {
var name = $("#a").val();
if (name == "") {
$("#nameerror").text("This field is required.");
alert('false');
} else {
alert('true');
$("#nameerror").remove();
}
//email1
var emailPattern = /\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\b/;
const email = $("#b").val();
if (email == "") {
$("#email1error").text("This field is required.");
isValid = false;
} else if (!emailPattern.test(email)) {
$("#email1error").text("Must be a valid email address.");
isValid = false;
} else {
$("#email1error").remove();
}
//eamil 2
var verify = $("#c").val();
if (verify == "") {
$("#email2error").text("This field is required.");
isValid = false;
} else if (verify !== email) {
$("#email2error").text("Must match first email entry.");
isValid = false;
} else {
$("#email2error").remove();
}
if (isValid == false) {
event.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="javascript:alert('ok')">
<label for="name"> Name:</label>
<input type="text" name="name" id="a"><span>*</span>
<div id="nameerror"></div><br>
<label for="email">Email Address:</label>
<input type="text" name="email" id="b"><span>*</span>
<div id="email1error"></div><br>
<label for="verify">Verify Email:</label>
<input type="text" name="verify" id="c"> <span>*</span>
<div id="email2error"></div><br>
<input type="submit" value="submit" />
</form>
<div></div>
I am trying to validate form but whenever I click submit button it says:
ReferenceError: check_text is not defined
even though variable is present in local scope.
<form class="input-text-box" method="post" action="">
<input type="text" id="uname" name="uname" placeholder="First Name" autocomplete="off" required>
<input type="text" id="ulastname" name="ulastname" placeholder="Last Name" autocomplete="off" required>
<input type="text" id="uuname" name="uuname" placeholder="Username" autocomplete="off" required>
<input type="text" id="contact" name="contact" placeholder="Contact" autocomplete="off" required>
<input type="email" id="email" name="uemail" placeholder="Email Address" autocomplete="off" required>
<input type="password" id="pass-1" name="upass1" placeholder="Password" autocomplete="off" required>
<input type="password" id="pass-2" name="upass2" placeholder="Confirm Password" autocomplete="off"required>
<input type="submit" value="Sign Up" id="submit-btn" onclick="validate()">
<p class="term-cond">By joining, you agree to our Terms of Service </p>
<p class="term-cond" style="margin:40px 0 0 65px;">Already a member? Sign In </p>
</form>
Below is the Javascript code which is intended to validate the values:
var msg="";
var DOMstring = {
firstName:'uname',
lastName:'ulastname',
userName:'uuname',
contact:'contact',
email:'email',
pass1:'pass-1',
pass2:'pass-2',
submit:'submit-btn'
}
function validate(){
var status = false;
var firstName = document.getElementById(DOMstring.firstName).value;
status = checkText(firstName,'First Name');
var lastName = document.getElementById(DOMstring.lastName).value;
status = checkText(lastName,'Last Name');
var userName = document.getElementById(DOMstring.userName).value;
status=checkText(userName,'Username');
var contact = document.getElementById(DOMstring.contact).value;
status = checkNumber(contact);
var pass1 = document.getElementById(DOMstring.pass1).value;
status = checkPass(pass1);
var pass2 = document.getElementById(DOMstring.pass2).value;
status = comparePass(pass1,pass2);
if(status == true){
alert("successfully created an account");
return true;
}else{
alert("Please consider the following error messages<br>"+msg);
return false;
}
}
function checkText(DOMname,name){
var ckeck_text = /^[A-Za-z]$/;
if(!check_text.test(DOMname)){
msg += name + ' cannot contain numbers or special character.<br>';
return false;
}
return true;
}
function checkNumber(DOMnumber){
var check_number = /^[0-9]{10}$/;
if(!check_number.test(DOMnumber)){
msg += 'Number contains 10 digit only<br>';
return false;
}
return true;
}
function checkPass(DOMpass1){
var check_pass = /^(?=.*[\d])(?=.*[!##$%^&*])[\w!##$%^&*]{8,16}$/;
if(!check_pass.test(DOMpass1)){
msg += 'Password field should contain alphanumeric values and special character<br> and should be in range from 8 to 16<br>';
return false;
}
return true;
}
function comparePass(DOMpass1,DOMpass2){
if(!DOMpass1 === DOMpass2){
msg += 'Both password does not match<br>';
return false;
}
return true;
}
I don't understand how there is no variable inside of same name if I had used let instead of var then this output is reasonable but with following method why it is not defined. If anything I am missing please help me to understand as I am completely new to Javascript.
You have a typo here var ckeck_text = /^[A-Za-z]$/;
I've made a form with required fields and custom error messages/validation, which all display/work correctly, however if the error is corrected, the form still cannot be submitted. This was working before I added the inline oninvalid checks. Not sure what I'm doing wrong.
Code:
<form role="form" method="post" action="contact-form.php">
<input type="text" class="input-field" name="name" id="name" placeholder="Name" required oninvalid="this.setCustomValidity ('Please enter your name.')" />
<input type="email" class="input-field" name="email" id="email" placeholder="Email" required />
<textarea name="message" class="textarea-field" id="message" placeholder="Message" required oninvalid="this.setCustomValidity ('Please enter your message.')"></textarea>
<input type="submit" value="Contact Me" class="btn btn-primary btn-xl" />
</form>
<script>
var email = document.querySelector( "#email" );
function setErrorMessage() {
if ( email.validity.valueMissing ) {
email.setCustomValidity( "Please enter your email address." );
} else if ( email.validity.typeMismatch ) {
email.setCustomValidity( "Please enter a valid email address." );
}
};
setErrorMessage();
email.addEventListener( "change", setErrorMessage );
</script>
JSFiddle: http://jsfiddle.net/44Lrgmjc/
Any help would be greatly appreciated!
Thanks.
I adjusted your javascript and added (key) a validate email function. here is a fiddle
function validate{
function email(){
if(form.email.value == "") {
alert("Please enter your email");
form.email.focus();
return false;
}
// regular expression to match only alphanumeric characters and spaces
var re = /^[\w ]+$/;
// validation fails if the input doesn't match our regular expression
if(!re.test(form.email.value)) {
alert("Invalid email address");
form.email.focus();
return false;
}
// validation was successful
return true;
}
function name(){
If(form.name.value == "") {
alert("Please enter your name");
form.name.focus();
return false;
}
// validation was successful
return true;
}
function msg{
if(form.message.value == "") {
alert("Please enter your message");
form.message.focus();
return false;
}
// validation fails if the input doesn't match our regular expression
if(!re.test(form.message.value)) {
alert("Invalid message content");
form.message.focus();
return false;
}
// validation was successful
return true;}}
</script>
<script>
function validateEmail()
{
var emailID = document.form.email.value;
atpos = emailID.indexOf("#");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.form.email.focus() ;
return false;
}
return( true );
}
<form role="form" method="post" action="contact-form.php" onsubmit="return validate(this);">
<input type="text" class="input-field" name="name" id="name" placeholder="Name" required oninvalid="alert ('Please enter your name.')"/>
<input type="email" class="input-field" name="email" id="email" placeholder="Email" required oninvalid="alert ('Please enter a valid email.')"/>
<textarea name="message" class="textarea-field" id="message" placeholder="Message" required oninvalid="alert ('Please enter your message.')" ></textarea>
<input type="submit" value="Contact Me" class="btn btn-primary btn-xl"/>
</form>
Reference
I've been working on this assignment for the longest while. My form validations weren't working previously but then I found out what the error was & everything was working perfectly.
Later on, I had made some changes to the code then deleted those changes and now the validations aren't working again & I can't seem to find what the problem is this time.
Below is my unfinished code:
function validateEmail() {
var email = document.getElementById('email').value;
if( email==null || email=="")
{
alert("Please input an email address");
}
}
function validateFName() {
var firstname = document.getElementById('firstname').value;
if( firstname==null || firstname=="")
{
alert("Please input a last name");
return false;
}
}
function validateLName() {
var lastname = document.getElementById('lastname').value;
if( lastname==null || lastname=="")
{
alert("Please input a last name");
}
}
function validateGender() {
var gender = document.getElementById('gender').value;
if( gender==null || gender=="")
{
alert("Please select a gender");
}
}
function validateDate() {
var date = document.getElementById('date').value;
if( date==null || date=="")
{
alert("Please select a date");
}
}
function validateVName() {
var vname = document.getElementById('vname').value;
if( vname==null || vname=="")
{
alert("Please input a victim's name");
}
}
function validateVEmail() {
var vemail = document.getElementById('vemail').value;
if( vemail==null || vemail=="")
{
alert("Please input a victim's email");
}
}
<div id="navi">
<nav>
<ul class="fancyNav">
<li id="home">Home</li>
<li id="news">TRUTH</li>
<li id="about">DARE</li>
</ul>
</nav>
</div>
<div id="box">
<form id="truth">
<h1> Truth </h1>
<label> First Name: </label> <input type="text" name="firstname" id="firstname" maxlength="30" placeholder="John" /> <br><br>
<label> Last Name: </label> <input type="text" name="lastname" id="lastname" maxlength="30" placeholder="Doe" /> <br><br>
<label> Email:</label> <input type="text" name="email" id="email" /> <br><br>
<label> Male </label><input type="radio" name="gender" id="gender" value="male"/>
<label> Female </label><input type="radio" name="gender" id="gender" value="female"/> <br><br>
<label> Date to be performed: </label><input type="date" name="date" id="date" /><br><br>
<h2> Victim </h2>
<label> Name: </label> <input type="text" name="vname" id="vname" maxlength="30" /><br><br>
<label> Email:</label> <input type="text" name="vemail" id="vemail" /> <br><br>
<h2> Please select a truth questions below </h2> <br>
<input type="radio" name="truth" value="q1"> Have you ever fallen and landed on your head? <br>
<input type="radio" name="truth" value="q2"> Have you ever return too much change? <br>
<input type="radio" name="truth" value="q3"> Have you ever been admitted into the hospital? <br>
<input type="radio" name="truth" value="q4"> Have you ever baked a cake? <br>
<input type="radio" name="truth" value="q5"> Have you ever cheated on test? <br>
<input type="radio" name="truth" value="q6"> Did you ever wish you were never born? <br>
<input type="radio" name="truth" value="q7"> Did you ever hide from Sunday School? <br><br>
<input type="submit" onclick="validateFName(); validateLName(); validateGender(); validateDate(); validateVName(); validateVEmail();" /> <br>
</form>
</div>
<input type="submit" onclick="validateFName(); validateLName(); validateGender(); v
typo in function name, onclick="validateFName()...
it should be validateLName()
and you define duplicate
<!DOCTYPE html>
<html> // remove this one
The best possible solution would be to not use any alert boxes at all but instead embed the error message next to the place of the error, but that would be more involved. Instead, to stick with this solution, first add an id to your submit button:
<button type="submit" id="truth-submit">Submit</button>
Then, attach an onclick handler through JavaScript (and rewrite your code to be more re-usable):
// Only run when the window fully loads
window.addEventListener("load", function() {
function validateEmail() {
var email = document.getElementById("email").value;
if (email === null || email === "") {
return "Please input an email address";
}
return "";
}
function validateFName() {
var firstname = document.getElementById("firstname").value;
if (firstname === null || firstname === "") {
return "Please input an first name";
}
return "";
}
function validateLName() {
var lastname = document.getElementById("lastname").value;
if (lastname === null || lastname === "") {
return "Please input an last name";
}
return "";
}
function validateGender() {
var gender = document.getElementById("gender").value;
if (gender === null || gender === "") {
return "Please select a gender";
}
return "";
}
function validateDate() {
var date = document.getElementById("date").value;
if (date === null || date === "") {
return "Please select a date";
}
return "";
}
function validateVName() {
var vname = document.getElementById("vname").value;
if (vname === null || vname === "") {
return "Please input a victim's name";
}
return "";
}
function validateVEmail() {
var vemail = document.getElementById("vemail").value;
if (vemail === null || vemail === "") {
return "Please input a victim's email";
}
return "";
}
document.getElementById("truth-submit").addEventListener("click", function(event) {
// Grab all of the validation messages
var validationMessages = [validateFName(), validateLName(),
validateGender(), validateDate(), validateVName(), validateVEmail()];
var error = false;
// Print out the non-blank ones
validationMessages.forEach(function(message) {
if (message) {
alert(message);
error = true;
}
});
// Stop submission of the form if an error occurred
if (error) {
event.preventDefault();
}
}, false);
}, false);
I am validating the email by adding the user and email to the list, the pattern that I provided is not working for some patterns like xyz.xyz kkk.kk and my message is not displaying when it is validating Here is my code..
HTML
<form id="myform">
<h2>Add a User:</h2>
<input id="username" type="text" name="username" placeholder="name">
<input id="email" type="text" name="email" placeholder="email">
<button onclick='return addUser();' type="submit">add user</button>
</form>
<h2>UsersList:</h2>
<ul id="users"></ul>
JS
function addUser(){
var list = document.getElementById('users');
var username =document.getElementById('username').value;
var email = document.getElementById('email');
var entry = document.createElement('li');
if (email.value != '')
{
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email.value));
list.appendChild(entry);
return false;
}
else {
email.className += 'errorclass';
email.innerHtml = "Please enter valid emailid";
return false;
}
CSS
.errorclass{
border: 1px red solid;
}
Replace
reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
with
reg = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
Refer JavaScript Regular Expression Email Validation