I have this on submit function that checks for the email field to have a properly formatted address. Works fine. However, I want the field to allow a null value as this particular input is optional and not required. I know this should be simple, Im missing the obvious. Someone point me in the right direction...
EDIT: Providing the entire form validation this time. As every time I just replace the email portion its breaking other pieces....
function validateSMSForm()
{
if (SMSForm.PID_Form.value.length < 4)
{
alert("Please enter a valid Partner ID");
return false;
}
if (SMSForm.area.value.length < 3)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (SMSForm.prefix.value.length < 3)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (SMSForm.line.value.length < 4)
{
alert("Please enter a valid 10-digit cell phone number");
return false;
}
<!-- EMAIL VALIDATION HERE
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(form.emailaddress.value))
{
return (true)
}
alert("Please enter a valid email address")
return (false)
-->
}
Add a check for empty/null string first:
if ((!form.emailaddress.value) || (/^\w+([.-]?\w+)#\w+([.-]?\w+)(.\w{2,3})+$/.test(form.emailaddress.value))) {
//handle valid e-mail
} else {
//handle invalid e-mail
}
Like this
Assuming
<form onsubmit="return validateSMSForm(this)">
JavaScript:
function isEmail(str) {
return !str || /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,})+$/.test(str);
}
function validateSMSForm(SMSForm) {
if (SMSForm.PID_Form.value.length < 4) {
alert("Please enter a valid Partner ID");
return false;
}
if (SMSForm.area.value.length < 3 ||
SMSForm.prefix.value.length < 3 ||
SMSForm.line.value.length < 4) {
alert("Please enter a valid 10-digit cell phone number");
return false;
}
if (!isEmail(SMSForm.emailaddress.value)) {
alert("Please enter a valid email address")
return false; //
}
return true; // allow submission
}
var email = form.emailaddress.value;
if (!email){ return true } // this what your looking for?
if (/^\w+([.-]?\w+)#\w+([.-]?\w+)(.\w{2,3})+$/.test(email))
{
return (true)
}
alert("Please enter a valid email address")
return (false)
Related
To validate the checkpoint the form will have to show an alert if
One of the inputs is empty
The password has less than 8 characters
Doesn't have a valid e-mail adress
The password must be a combination of charatacters , numbers and at least a capital letter
And finally the reset button will reset all the inputs to empty :
//Variable declaration
var username=document.forms["Registration"]["name"];
var e_mail=document.forms["Registration"]["email"];
var password=document.forms["Registration"]["psw1"];
var passwordcheck=document.forms["Registration"]["psw2"];
//add eventListener
username.addEventListener("blur", NameVerify, true);
e_mail.addEventListener("blur", EmailVerify, true);
password.addEventListener("blur", PasswordVerify, true);
passwordcheck.addEventListener("blur", PasswordVerify, true);
// validate the registration
function Validate(){
if (username.value=="")
{
alert("username is required");
username.focus()
return false;
}
if (e_mail.value=="")
{
alert("Email is required");
e_mail.focus()
return false;
}
if (password.value=="")
{
alert("Password is required");
password.focus()
return false;
}
if (passwordcheck.value=="")
{
alert("Re-enter your password");
passwordcheck.focus()
return false;
}
if(password.value != passwordcheck.value){
alert("Password do not match!!")
passwordcheck.focus()
return false;
}
}
//check the username value
function NameVerify(username){
if (username.value !=0) {
document.querySelector.backgroundColor = lightGrey;
return true;
}
}
//check the e_mail
function EmailVerify(e_mail){
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.`\w{2,3})+$/.test(Registration.email.value))`
{
return (true)
}
alert("You have entered an invalid email address!")
e_mail.focus()
return (false)
}
//check the password
function PasswordVerify(password){
var psw = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,20}$/;
if(password.value.match(psw))
{
alert('Correct, try another...')
return true;
}
else
{
alert('Wrong!!')
return false;
}
}
// clear all text inputs when the page is loaded
function clearInp() {
document.getElementsByTagName("input").value = "";
return true;
}
//reset all text fields
function Reset() {
document.querySelector("#Registration").reset();
return true;
}
None of this requires any JavaScript at all.
One of the inputs is empty
<input type="text" required />
The password has less than 8 characters
<input type="password" minlength="8" />
Doesn't have a valid e-mail adress
<input type="email" />
The password must be a combination of charatacters , numbers and at least a capital letter
<input type="password" pattern="(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,}" />
And finally the reset button will reset all the inputs to empty
<input type="reset" value="Reset form" />
Once you've eliminated all JavaScript code from your form, you will find that your form no longer has any JavaScript errors ;)
window.onload=alert("please,Sign Up first");
window.onload=pageload;
function pageload() {
var signup=document.getElementById("signup");
signup.onsubmit=signupp;
}
function signupp(){
var st=document.getElementById("st").value;
var ls=document.getElementById("ls").value;
if (st=="First name" || st=="") {
alert("please enter your first name");
return false;
}
else if (ls=="Last name" || ls=="") {
alert("please enter your last name");
return false;
}
// what should i type here to move to loginn function ?
}
function loginn(){
var st=document.getElementById("st").value;
var ls=document.getElementById("ls").value;
if(username==""){
alert("please enter your username or your phone number");
return false;
}
if(password==""){
alert("please enter your password");
return false;
}
}
You can set the login wrapper div via CSS to:
#loginform{display:none;}
And then after registration set via JS to:
var loginform=document.getElementById("loginform");
loginform.style.display = 'block';
I'm trying to validate a form that will send an email. At the moment the button returns formCheck() onclick. Which is meant to display a popup respective of field completetion.
I'm new to JS so I'm having a little trouble working out what I'm doing wrong as the outcome is always the else "Thanks".
<script>
function formCheck() {
if (document.getElementById("Name") === "")
{
alert("please enter name");
}
else if (document.getElementById("Email") === "")
{
alert("Please enter an email address");
}
else if (document.getElementById("Name") && document.getElementById("Email") === "")
{
alert("Please enter a Name and Email address");
}
else {
alert("Thanks");
}
}
</script>
To me it looks like I'm either not using an if statementcorrectly or its not picking up the fields are empty when defined as "". If anybody can point me in the right direction it would be much appreciated.
You should be comparing the value instead of the object itself:
document.getElementById("Name").value
When I enter the correct email format like "abcd#gmail.com", I'm getting an invalid email address alert. What's the mistake which I have done in my code?
var pattern = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (element.value == '') {
alert('Please enter valid email address');
element.focus();
element.value = '';
return false;
} else {
if (!pattern.test(element)) {
alert('Invalid Email Address');
element.focus();
element.value = '';
return false;
} else {
alert("Email is valid");
return true;
}
}
}
Email:<input type="text" id="email" onblur="return validateEmail(this)" />
Contact:<input type="text" id="contact"/>
Because an object is not a string
Look at what you are comparing, it is no value
if (element.value == '') { <-- you reference the value here
if (!pattern.test(element)) <-- you reference the element here, not the value
so yoour reg expression is checking
!pattern.test("[object Object]")
add the missing .value and it should work
if (!pattern.test(element.value))
I am trying to remake a jQuery script by (http://jorenrapini.com/blog/javascript/the-simple-quick-and-small-jquery-html-form-validation-solution). This script is checking if a from is filled, if not a error message will appear.
What I want to do is to only get the error message when one of two form input-fields are filled out, if none of them are then they should be ignored. The form fields are named "firstinput" and "secondinput" (you can see their id in the code).
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Can anybody please help me with a solution, I would really appreciate it.
/A girl that spend a LOT of time solving this without luck :(
I would wrap your for loop in a conditional that evaluates if one or the other has a value.
if($("#field1").val() == "" && $("#field2").val() == ""){
//Ignore
}else{
//Do something
}
$(document).ready(function(){
// Place ID's of all required fields here.
required = ["firstinput", "secondinput"];
// If using an ID other than #email or #error then replace it here
email = $("#email");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
if($("#firstinput").val() != "" || $("#secondinput").val() != "")
{
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});