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
Related
I am validating a login form and for each error with the form validation (e.g. incorrect username or email format), I want to display an unordered list containing the errors. I know how to validate the input etc. but I can't figure out how to add in an unordered list in my if statements. I know these if statements may be inefficient for validation and incorporating an unordered list will recreate an unordered list in each if statement. but I am required to learn JavaScript in 3 weeks. Here is my HTML code:
let fullName = document.getElementById("fullName");
let formErrors = document.getElementById("formErrors");
let email = document.getElementById("email");
let emailRegex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/
let password = document.getElementById("password");
let passwordConfirm = document.getElementById("passwordConfirm");
let submitButton = document.getElementById("submit");
function checkForm() {
// TODO: Perform input validation
if (fullName.value < 1) {
formErrors.style.display = "block";
formErrors.innerHTML = "Missing full name";
};
if (email != emailRegex) {
formErrors.style.display = "block";
formErrors.innerHTML = "Missing email";
}
if (password.value < 10 || password.value > 20) {
formErrors.style.display = "block";
formErrors.innerHTML = "Password must be between 10 and 20 characters."
}
}
document.getElementById("submit").addEventListener("click", function(event) {
checkForm();
// Prevent default form action. DO NOT REMOVE THIS LINE
event.preventDefault();
});
<h1>User Registration</h1>
<form>
<label for="fullName">Full Name</label> <br>
<input type="text" id="fullName" class="defaulx"> <br>
<label for="email">Email</label> <br>
<input type="email" id="email" class="defaulx"> <br>
<label for="password">Password</label> <br>
<input type="password" id="password" class="defaulx"> <br>
<label for="passwordConfirm">Confirm Password</label> <br>
<input type="password" id="passwordConfirm" class="defaulx"> <br>
<input type="submit" id="submit" value="Register">
</form>
<div id="formErrors" style="display: none;"></div>
</div>
As you know how to validate and do the conditions, I am just adding only a fragment to support your code. Hopes this will help you to create a list of errors.
function checkForm() {
// TODO: Perform input validation
var ul = document.createElement('UL');
if (true) {
var li = document.createElement('LI');
li.innerHTML = "Missing full name";
ul.appendChild(li);
};
if (true) {
var li = document.createElement('LI');
li.innerHTML = "Missing email";
ul.appendChild(li);
}
if (true) {
var li = document.createElement('LI');
li.innerHTML = "Password must be between 10 and 20 characters."
ul.appendChild(li);
}
document.getElementById('formErrors').appendChild(ul);
}
checkForm();
<div id="formErrors"></div>
What the code does is
var ul = document.createElement('UL');
this will create a <ul></ul> element.
on each if
var li = document.createElement('LI');
this will create a <li></li> element
li.innerHTML = "Missing email";
this will set the html value to it.
ul.appendChild(li);
this will append the li to the ul providing <ul><li></li></ul>
Here's my approach:
let fullName = document.getElementById("fullName");
let formErrors = document.getElementById("formErrors");
let email = document.getElementById("email");
let emailRegex = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,5}$/
let password = document.getElementById("password");
let passwordConfirm = document.getElementById("passwordConfirm");
let submitButton = document.getElementById("submit");
function checkForm() {
// TODO: Perform input validation
const errors = []
if (fullName.value < 1) {
errors.push("Missing full name");
}
if (!emailRegex.test(email.value)){ // note this change
errors.push("Missing email");
}
if (password.value < 10 || password.value > 20) {
errors.push("Password must be between 10 and 20 characters.");
}
let ul = document.createElement("ul");
errors.forEach(error => {
let li = document.createElement("li");
li.innerHTML = error;
ul.appendChild(li);
});
formErrors.innerHTML = ""; // clear what had been displayed
formErrors.appendChild(ul);
}
document.getElementById("submit").addEventListener("click", function (event) {
checkForm();
// Prevent default form action. DO NOT REMOVE THIS LINE
event.preventDefault();
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>User Registration</title>
<link href="style.css" rel="stylesheet">
<script src="register.js" defer></script>
</head>
<body>
<h1>User Registration</h1>
<form>
<label for="fullName">Full Name</label> <br>
<input type="text" id="fullName" class="defaulx"> <br>
<label for="email">Email</label> <br>
<input type="email" id="email" class="defaulx"> <br>
<label for="password">Password</label> <br>
<input type="password" id="password" class="defaulx"> <br>
<label for="passwordConfirm">Confirm Password</label> <br>
<input type="password" id="passwordConfirm" class="defaulx"> <br>
<input type="submit" id="submit" value="Register">
</form>
<div id="formErrors"></div>
</div>
</body>
</html>
I have a problem, I made a form validation in javascript and after all validation checks I put innerHtml += "actually error message" and the problem is how many times I click the submit button it writes out the message. Someone can help me to solve this? Or make this more elegant or better logic. I'm a beginner.
function regvalidate() {
var errortable = document.getElementById('log');
var x = document.forms["regform"]["username"].value;
var y = document.forms["regform"]["email"].value;
var z = document.forms["regform"]["pass1"].value;
var b = document.forms["regform"]["pass2"].value;
if (x == "" || y == "" || z == "" || b == "") {
errortable.innerHTML = 'Cant be empty field';
return false;
}
var regexEmail = /\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*/;
var email = document.getElementById("email");
if (regexEmail.test(email.value)) {} else {
errortable.innerHTML += 'Invaild email address';
return false;
}
password1 = regform.pass1.value;
password2 = regform.pass2.value;
if (password1 != password2) {
errortable.innerHTML += 'Two pass dosent match';
return false;
}
}
<div id="log"></div>
<form id="regform" class="form-signin" action="#" method="post">
<input type="text" id="username" class="form-control" placeholder="username" name="username">
<input type="email" id="email" class="form-control" placeholder="email" name="email">
<input type="password" id="pass1" class="form-control" placeholder="password" name="password_1">
<input type="password" id="pass2" class="form-control" placeholder="password again" name="password_2">
</br>
<button class="btn btn-lg btn-primary btn-block" type="submit" onClick="return regvalidate()" name="register_btn">Register</button>
</form>
just remove the + before =like the following
errortable.innerHTML += 'Two pass dosent match';
or do it like
errortable.innerHTML = '';
errortable.innerHTML += 'Two pass dosent match';
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>
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 am adding username and email to the userlist and validating email when adding. Validation is working when the page loads for the first time, If I tried to enter invalid email for second time and click the add button it is not working..
<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>
<script type="text/javascript">
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-Z0-9-.]+$/;
if (reg.test(email.value) == true) {
entry.appendChild(document.createTextNode(username + ' ' + email.value));
list.appendChild(entry);
return false;
}
else {
email.className += 'errorclass';
return false;
}
}
else{
alert("Please Enter Email Id");
return false;
}
}
</script>
<style>
.errorclass{
border:1px red solid;
}
</style>
Each time there is a validation error you add 'errorclass' to the email class. So the second time is "errorclasserrorclass" that is not defined in the css.
Use:
email.setAttribute('class','errorclass')