Failed to validate email address with regular expression - javascript

I would like to run my page to test out whether my validation works. However, it does not work with email address. I have added regular expression for email address. It doesn't validate fully.
I entered a#live without typing .com it able to accept it. I assume this is because i type input="email" Correct me wrong. Is it due to the wrong regular expression or maybe the way I placed my code?
javascript
function validate(){
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value;
var email = document.getElementById('email').value;
var emailReg = '/^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/';
var re = /^[\w ]+$/;
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(email=="")
{
alert('Please fill in email fields');
return false;
}
else if(fname=="")
{
alert('Please fill in first name fields');
return false;
}
else if(lname=="")
{
alert('Please fill in last name fields');
return false;
}
return true;
}
register.php
<form name="registrationForm" method="post" id="registrationForm" class="registrationForm" action="processRegister.php" onclick="validate">
<div class='input1'>
<span id="emailAddress-label" class="help"></span>
<input class="regemailaddr" id="emailAddress" name="emailAddress" type="email" placeholder="Email Address " value="" required>
</div>
<br>
<span id="fname-label" style="margin-bottom:" class="help"></span>
<input id="fname" name="fname" type="text" placeholder="First Name " class="fname" value="" required>
<span id="lname-label" class="help"></span> <input id="lname" name="lname" type="text" placeholder="Last Name " class="lname" value="<?php echo $user_profile["lname"]; ?>" required>
<br>
<button class="greybtn" type="submit" id="submitButton">Submit</button>
<button class="cancelbtn" type="button" id="cancelButton" onclick="window.location='#';return false;">Cancel</button>
</form>

You have defined a regular expression
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
but you do not test against it
var isEmail = emailReg.test(email);

Related

Variable scope inside function Javascript

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]$/;

Checking if the input fields are filled in properly (pure javascript)

I almost complete the form validation, but the only pain in the ass for me is:
1) Input fields should be checked themselves when some have filled in the input field and click outside the input box.
2) when someone leaves all the input fields empty and clicked on the send button.
Anyone an idea how I can fixed that?
function validateForm() {
var name = document.getElementById("name");
var email = document.getElementById("email");
var nameValidation = document.getElementById("nameValidation");
var emailValidation = document.getElementById("emailValidation");
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (name.value.length == "") {
nameValidation.innerHTML = " Please fill in your name";
name.focus();
} else {
nameValidation.innerHTML = " Right";
}
if(!filter.test(email.value) || (email.value.length == "")) {
emailValidation.innerHTML = " Please enter a valid email address";
email.focus();
}
else {
emailValidation.innerHTML = " Right!";
}
}
<form action="#" id="form" method="post" name="form">
<img id="close" src=IMAGE/close.png alt="close-button" onclick="div_hide()"/>
<h3><b>Application form</b></h3>
<input id="name" class="application" name="name" placeholder="Name" type="text" maxlength="30" /><span id="nameValidation"></span><br/>
><input id="email" class="application" placeholder="Email" type="text" maxlength="254" /><span id="emailValidation"></span>
<div id="upload-box">
<input id="upload" class="application upload" type="file"/>
<input id="submit" class="application apply-button" type="button" onclick="validateForm()" value="Send"/>
</div>
</form
<input type="email" required />
Job done.

Make form validation via custom attributes

please help me to make validation via input tag's custom attribute (in my case: validation). Help me to change my code that it becomes more dynamic and reusable.
var validation = function validation(){// out of grid - rename js name
//validate first name - only letters
var only_letters = /^[A-Za-z]+$/;// allow only letters
if(firstName.value.length === 0){
document.getElementsByClassName("error")[0].innerHTML="First Name is required";
formIsValid = false;
}
else
if(firstName.value.match(only_letters)){
document.getElementsByClassName("error")[0].innerHTML="";
}
else{
document.getElementsByClassName("error")[0].innerHTML="Only characters allowed";
formIsValid = false;
}
//validate email
var email_letters = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(email.value.length === 0){
document.getElementsByClassName("error")[2].innerHTML="Email is required";
formIsValid = false;
}
else
if(email.value.match(email_letters)){
document.getElementsByClassName("error")[2].innerHTML="";
}
else{
document.getElementsByClassName("error")[2].innerHTML="Incorrect email format";
formIsValid = false;
}
<form id="user_form" method="post">
<p> <input type="text" name="first_name" id="first_name" placeholder="First Name" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
<p><input type="text" name="email" id="email" autocomplete="off" placeholder="Email" validation="isRequired, correctFormat" /></p>
<span class="error"></span>
</form>
Well if you look really carefully, you kinda only have one method in it's essence.
Create a method that gets the element, a regex expression, the response container, and that returns a string.
It would look something like this:
function validateMePls(var field, var regex, var placeholder){
var isValid = "";
/** do all your checks here (length, regex, etc), appending 'isValid', then return it at the end */
};
var isValid = validateMePls(email, email_letters, document.getElementsByClassName("error")[2]);
/** and now you check 'isValid' for something in it, so you know if you have an error or not */
That's basically how an optimized version of your code would look.
Sorry for the 'close to Java' code but I haven't been doing any Javascript lately.
Good luck.
You could utilize placeholder attribute, required attribute, setCustomValidity() set to placeholder at invalid event
var inputs = document.querySelectorAll("input:not([type=submit])");
for (var i = 0; i < inputs.length; i++) {
inputs[i].oninvalid = function(e) {
e.target.setCustomValidity(e.target.placeholder)
}
}
<form id="user_form" method="post">
<label for="first_name">
<input type="text" pattern="[a-zA-Z]+$" name="first_name" id="first_name" placeholder="Input letters a-z A-Z" required />
</label>
<br>
<label for="email">
<input type="email" name="email" id="email" autocomplete="off" placeholder="Valid Email is required" required />
</label>
<br>
<input type="submit" />
</form>

Custom Error Messages in HTML5 Required Form Fields

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

Why isn't my instantaneous validation displaying anything?

I have a form that has a number of fields on it. When the user inputs anything, the field should automatically begin sending feedback as to whether or not the input is valid. The javascript code listed is suppose to handle the instantaneous feedback but it gives no reply whatsoever. It is also suppose to stop the form from being submitted if any of the user's input does not match the regular expressions. The regular expressions don't work either but they were working perfectly fine before I used the innerHTML. I would go back to using alerts if using innerHTML wasn't mandatory.
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]{5,40}$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
} else {
return valid;
}
}
function test() {
var result = true;
if (!insert()) {
result = false;
}
return result;
}
This is the html form that the javascript function is referencing.
<form name="Insert" id="I2" action="order.php" method="post" style="display: none;" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off" autofocus>Name <span id="MessNM"></span>
<br>
<input type=email id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type=password id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type=password id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type=text id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type=text id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
There are several issues I see.
You have style="display: none;" on the form which makes the whole form invisible.
Your validation function returns false on the first failed validation which means you're only going to show an error message for the first invalid field, e.g. if e-mail address and zip code are invalid you'll only get a message for e-mail address.
The regular expression for the address validation is broken.
When the password confirmation error is fixed the error message doesn't clear.
By the fact that you say it was working when you used alerts, I'm guessing the main issue you're talking about is caused by the fact that each field validation returns false. You probably just had alerts before and returned a boolean at the end of the function. Here's a solution that addresses that issue and the others I mentioned above.
<form name="Insert" id="I2" action="order.php" method="post" onsubmit="return test()">
<p align="left">
<div id="texter">
<input type=text id="name" required="required" onkeyup="insert()" name="name" autocomplete="off"/>Name <span id="MessNM"></span>
<br>
<input type="email" id="email" required="required" onkeyup="insert()" name="email">Email Address <span id="MessEM"></span>
<br>
<input type="password" id="password" required="required" onkeyup="insert()" name="password">Password <span id="MessPS"></span>
<br>
<input type="password" id="passwordcheck" required="required" onkeyup="insert()" name="passwordcheck">Confirm Password <span id="MessPSC"></span>
<br>
<input type="text" id="address" required="required" onkeyup="insert()" name="address">Address <span id="MessAD"></span>
<br>
<input type="text" id="zipcode" required="required" onkeyup="insert()" name="zipcode">Zipcode <span id="MessZC"></span>
<br>
</div>
<input type="submit" value="submit" onclick="test()">
<input type="reset" value="Clear All">
<br>
<br>
</form>
function insert() {
var valid = true;
document.getElementById("MessNM").innerHTML = "";
if (!document.getElementById("name").value.match(/^^[A-Z]{1}[a-z]{3,7}$/)) {
document.getElementById("MessNM").innerHTML = " Please input a proper name.";
valid = false;
}
document.getElementById("MessPS").innerHTML = "";
if (!document.getElementById("password").value.match(/^[a-zA-Z0-9]{4,8}$/)) {
document.getElementById("MessPS").innerHTML = " Please input a proper password with numbers and letters.";
valid = false;
}
document.getElementById("MessPSC").innerHTML = "";
if (document.getElementById("passwordcheck").value != document.getElementById("password").value) {
document.getElementById("MessPSC").innerHTML = " Password does not match.";
valid = false;
}
document.getElementById("MessAD").innerHTML = "";
if (!document.getElementById("address").value.match(/^[a-zA-Z0-9\s,'-]*$/)) {
document.getElementById("MessAD").innerHTML = " Address is not valid";
valid = false;
}
document.getElementById("MessZC").innerHTML = "";
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
if (!document.getElementById("zipcode").value.match(/^[0-9]{5}(-[0-9]{4})?$/)) {
document.getElementById("MessZC").innerHTML = " Please input a proper Zipcode.";
valid = false;
}
return valid;
}

Categories

Resources