jQuery form validation issue - javascript

I'm not using any jQuery plugin to validate the form, just plain jQuery. My issue is that after it validates all the input elements, even if it shows the error message to the user, it will still submit the form without the user correcting the error.
To elaborate, my form has 3 input elements. with jQuery validation, if all the 3 elements are empty, and the user clicks on the Submit button, it will throw an error highlighting the first element. If the user does not correct the error, but clicks on the submit button again, it will highlight the second element [with the first input element still highlighted]. Likewise for the 3rd element. Now if the user without correcting the error (that is, the input elements are still highlighted) clicks on the submit button again, it will submit the form. Ideally, it should keep on highlighting the first input element till the user corrects his error and then validate the 2nd input element and so on. .and this is what I want to do.
jQuery code:
$(function() {
/*Form Validation*/
$("#name")
.focus(function() {
if ($(this).val() == "Your Name" || $(this).val() == "Field cannot be blank" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Name");
}
})
.keyup(function() {
$("#name").val($(this).val());
}),
$("#email")
.focus(function() {
if ($(this).val() == "Your Email" || $(this).val() == "Field cannot be blank" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Email");
}
})
.keyup(function() {
$("#email").val($(this).val());
}),
$("#msg")
.focus(function() {
if ($(this).val() == "Your Message" || $(this).val() == "You forgot to enter your message" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Message");
}
})
.keyup(function() {
$("#msg").val($(this).val());
})
});
function checkForm(form) {
var cssObj = {
'background-color' : 'red',
'border' : 'green'
}
if ($("#name").val() == "" || $("#name").val() == "Your Name") {
$("#name").css(cssObj);
$("#name").val('Field cannot be blank');
return false;
}
else if ($("#email").val() == "" || $("#email").val() == "Your Email") {
$("#email").css(cssObj);
$("#email").val('Field cannot be blank');
return false;
}
else if ($("#msg").val() == "" || $("#msg").val() == "Your Message") {
$("#msg").css(cssObj);
$("#msg").val('You forgot to enter your message');
return false;
}
else {
return true;
}
}
. .html:
<form action="somepage.php" method="post" id="contactform">
<div class="container">
<div class="field">
<input type="text" tabindex="1" value="Your Name" name="name" id="name" /><br />
</div>
<div class="field">
<input type="text" tabindex="2" value="Your Email" name="name" id="email" /><br />
</div>
<div class="field">
<textarea tabindex="3" name="msg" id="msg">Your Message</textarea><br />
</div>
<input type="button" onclick="return checkForm('contactform');" id="sb" value="Submit" class="submitbtn" />
</div>
</form>

Your checkform function behaves like it should.
However here is a possible correction
function checkForm(form) {
var cssObj = {
'background-color' : 'red',
'border' : 'green'
}
if ($("#name").val() == "" || $("#name").val() == "Your Name" || $("#name").val() == 'Field cannot be blank' ) {
$("#name").css(cssObj);
$("#name").val('Field cannot be blank');
return false;
}
else if ($("#email").val() == "" || $("#email").val() == "Your Email" || $("#email").val() = 'Field cannot be blank' ) {
$("#email").css(cssObj);
$("#email").val('Field cannot be blank');
return false;
}
else if ($("#msg").val() == "" || $("#msg").val() == "Your Message" || $("#msg").val() == 'You forgot to enter your message' ) {
$("#msg").css(cssObj);
$("#msg").val('You forgot to enter your message');
return false;
}
else {
return true;
}
}
Please look at http://en.wikipedia.org/wiki/Idempotence too.

Related

Trying to convert this big if else statement into a loop

Hi I'm trying to make this code more clean. I struggle with arrays and loops and have no idea how to convert this into into a loop. This is javascript for a form on an html page and if they leave a field blank, when they hit submit it should return an alert box and if everything is submitted properly it should confirm with them. There's also a reg exp for an acceptable postal code entry.
function validate()
{
var register = document.forms[0];
if (register.fname.value === "")
{
alert("Please fill out your first name.");
return false;
}
else if(register.lname.value === "")
{
alert("Please fill out your last name.");
return false;
}
else if(register.address.value === "")
{
alert("Please fill out your address.");
return false;
}
else if(register.postal.value ==="")
{
alert("Please enter a valid postal code.");
return false;
}
else if(!checkPostal(register.postal.value))
{
alert("Please enter a valid postal code.");
return false;
}
else if(register.eAddress.value === "")
{
alert("Please fill out your email address.");
return false;
}
return confirm("Is the information correct?");
}
//postal code regExp
function checkPostal()
{
var myReg = /^[A-Z]\d[A-Z] ?\d[A-Z]\d$/ig;
return myReg.test(document.getElementById("postal").value);
}
You can make this a pure HTML solution if you want to reduce javascript:
inputs have a required attr ref
additionally, inputs have a pattern attr ref that supports regex.
This kind of solution lets the browser handle feedback
<form>
<label>first name:
<input type="text" name="fname" required
minlength="1">
</label><br/>
<label>last name:
<input type="text" name="lname" required
minlength="1">
</label><br/>
<label>postal code:
<input type="text" name="zip" required pattern="^[A-Z]\d[A-Z] ?\d[A-Z]\d$"
minlength="1">
</label><br/>
<input type="submit" />
</form>
$.each( $( "#input input" ), function( key, element ) {
if( !$(element).val() ) {
$( "#error" + key ).text( "Input " + $( element ).attr( "name" ) + " is required");
return false;
}
});
Set your message as attribute on each element of the form like this:
<form method="POST" action="submit.php">
<input id="item1" type="text" value="" data-message="My error message" data-must="true">
...//do the same for other elements...
</form>
Now loop like below
var elements = document.forms[0].elements;
for (var i = 0, element; element = elements[i++];) {
if (element.getAttribute("must") && element.value === ""){
alert(element.getAttribute("message"));
return false;
}
}
return confirm("Is the information correct?");

check the empty field instantly in jquery

I have to check the fields of my form if they are empty and display an error message in front of each empty field, but I can not find how to check the fields of a form and display an error message they are empty with jQuery. I tried with keyup but it does not do it instantly. Do you know how to do it in jQuery?
$(function() {
$("#myButton").click(function() {
valid = true;
if ($("#name").val() == "") {
$("#name").next(".error-message").fadeIn().text("Please enter your name")
valid = false;
} else if (!$("#name").val().match(/^[a-z]+$/i)) {
$("#name").next(".error-message").fadeIn().text("Please enter a valid name")
valid = false;
} else {
$("#name").next(".error-message").fadeOut();
}
if ($("#firstName").val() == "") {
$("#firstName").next(".error-message").fadeIn().text("Please enter your first name")
valid = false;
} else if (!$("#firstName").val().match(/^[a-z]+$/i)) {
$("#firstName").next(".error-message").fadeIn().text("Please enter a valid first name")
valid = false;
} else {
$("#firstName").next(".error-message").fadeOut();
}
if ($("#phone").val() == "") {
$("#phone").next(".error-message").fadeIn().text("Please enter your phone")
valid = false;
} else if (!$("#phone").val().match(/^[0-9]+$/i)) {
$("#phone").next(".error-message").fadeIn().text("Please enter a valid phone")
valid = false;
} else {
$("#phone").next(".error-message").fadeOut();
}
return valid;
});
});
.error-message {
display: none;
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" id="myForm">
<fieldset>
<legend>Contact us</legend>
<label>Your name:</label>
<input type="text" name="name" id="name">
<span class="error-message">error</span>
<br />
<label>Your First name:</label>
<input type="text" name="firstName" id="firstName">
<span class="error-message">error</span>
<br />
<label>Your phone:</label>
<input type="text" name="phone" id="phone">
<span class="error-message">error</span>
<br />
<input type="submit" value="Submit" id="myButton">
</fieldset>
</form>
check my input for example , u may use onkeyup (when delete content)
my function checks how strong password is and if it's not empty
function checkPasswd(el, but) {
let password = $(el).val();
const strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})");
if (strongRegex.test(password)) {
$(el).css({
'background-color': '#58bc62'
});
$(but).attr("disabled", false);
} else {
if (password == "") {
$(el).css({
'background-color': 'white'
});
$(but).attr("disabled", true);
} else {
$(el).css({
'background-color': '#e57777'
});
$(but).attr("disabled", true);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" name="password" id="password" placeholder="new password..." onkeyup="checkPasswd('#password', '.saveToDbButton')" class="add_user" required>
I succeeded
$("#name").focusout(function () {
if (!$(this).val()) {
$("#name").next(".error-message").fadeIn().text("Please enter your name");
name = false;
}
else if(!$("#name").val().match(/^[a-z]+$/i)){
$("#name").next(".error-message").fadeIn().text("Please enter a valid name");
name = false;
}
else{
$("#name").next(".error-message").fadeOut();
}
});
$("#firstName").focusout(function () {
if (!$(this).val()) {
$("#firstName").next(".error-message").fadeIn().text("Please enter your first name");
firstName = false;
}
else if(!$("#firstName").val().match(/^[a-z]+$/i)){
$("#firstName").next(".error-message").fadeIn().text("Please enter a valid first name");
firstName = false;
}
else{
$("#firstName").next(".error-message").fadeOut();
}
});
$("#phone").focusout(function () {
if (!$(this).val()) {
$("#phone").next(".error-message").fadeIn().text("Please enter your phone");
phone = false;
}
else if(!$("#phone").val().match(/^[0-9]{10}$/i)){
$("#phone").next(".error-message").fadeIn().text("Please enter your phone");
phone = false;
}
else{
$("#phone").next(".error-message").fadeOut();
}
});

jQuery validation is not working in contact form

I want validation through jQuery. I have two fields name and email. email blank field validation is not working.
Here is my code,
<form>
Name : <input type="text" name="name" id="name"><br>
<span id="nameSpan"></span>
<br>
Email:<input type="email" name="email" id="email1"><br>
<span id="emailSpan"></span>
<br>
<input type="submit" id="submitBtn">
</form>
javascript
$(document).ready(function(){
var name = $("#name").val();
var email1 = $("#email1").val();
$("#submitBtn").on("click", function(){
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});
Please guide me where am I wrong. Thanks in advance
You are checking values of inputs only once while page load. We need to check them everytime so lets move this part into onclick function.
$(document).ready(function(){
$("#submitBtn").on("click", function(){
var name = $("#name").val();
var email1 = $("#email1").val();
if(name == '')
{
$("#nameSpan").html('Name is required');
return false;
}
else
{
$("#nameSpan").html('');
}
if(email1 == '')
{
$("#emailSpan").html('Email is required');
return false;
}
else
{
$("#emailSpan").html('');
}
});
});

js function call help needed

i have the code as shown below,
this is the html part.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="regi.js" ></script>
</head>
<body class="regbody">
<form align="center" method="POST" action="submit()" name="regform">
<div id="regpgdiv">
<span class="indextext">Fill in the details below to get registered! </span><br><br><br><br><br><br>
<input type="text" name="regfname" id="ip" value="Enter name" onfocus="if(this.value == 'Enter name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter name'; }" /> <br><br>
<input type="text" name="reguname" id="ip" value="Enter Desired Username" onfocus="if(this.value == 'Enter Desired Username') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter Desired Username'; }" /> <br><br>
<input type="password" name="regpwd" id="ip" value="Select Password" onfocus="if(this.value == 'Select Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Select Password'; }" /> <br><br>
<input type="password" name="cregpwd" id="ip" value="Re-enter Password" onfocus="if(this.value == 'Re-enter Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Re-enter Password'; }" /> <br><br>
<input type="submit" value="Register" id="credsub" >
</div>
</form>
</body>
and the js code is below for the Submit function
function Submit(){
var fname = document.form.regfname.value,
uname= document.form.reguname.value,
fpassword = document.form.regpwd.value,
cfpassword= document.form.cregpwd.value;
if( uname == "" || uname == "Enter Desired Username")
{
document.form.reguname.focus() ;
document.getElementById("errorBox").innerHTML = "enter the username";
return false;
}
if( fname == "" || fname == "Enter name")
{
document.form.regfname.focus() ;
document.getElementById("errorBox").innerHTML = "enter the first name";
return false;
}
if(fpassword == "" || fpassword == "Select password" )
{
document.form.regpwd.focus();
document.getElementById("errorBox").innerHTML = "enter the password";
return false;
}
if (!(cfpassword.equals(fpassword)) )
{
document.form.cregpwd.focus();
document.getElementById("errorBox").innerHTML = "doesnt match";
return false;
}
if(fname != '' && fpassword != '' && cfpassword != '' && uname!= ''){
document.getElementById("errorBox").innerHTML = "form submitted successfully";
}
}
when i click the regiter button, it says this webpage has npt been found.
i am new to javascript and need help. thanks in advance.
Yet Another Update - I realised there are errors in your Javascript code for referencing DOM objects (as well as a typo in your validation logic), below are the working modified code. In short, I have added id's to the form elements for referencing, and in your validation logic, you should be check Select Password instead of Select password.
The HTML form
<form align="center" method="POST" action="TARGET-PAGE-TO-HANDLE-DATA" name="regform" id="regform" onsubmit="return Submit()">
<div id="regpgdiv">
<span class="indextext">Fill in the details below to get registered! </span><br><br><br><br><br><br>
<input type="text" name="regfname" id="fname" value="Enter name" onfocus="if(this.value == 'Enter name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter name'; }" /> <br><br>
<input type="text" name="reguname" id="uname" value="Enter Desired Username" onfocus="if(this.value == 'Enter Desired Username') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter Desired Username'; }" /> <br><br>
<input type="password" name="regpwd" id="regpwd" value="Select Password" onfocus="if(this.value == 'Select Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Select Password'; }" /> <br><br>
<input type="password" name="cregpwd" id="cregpwd" value="Re-enter Password" onfocus="if(this.value == 'Re-enter Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Re-enter Password'; }" /> <br><br>
<input type="submit" value="Register" id="credsub" >
</div>
</form>
JS
function Submit() {
var fname = document.getElementById("fname");
var uname= document.getElementById("uname");
var fpassword = document.getElementById("regpwd");
var cfpassword= document.getElementById("cregpwd");
if (uname.value == "" || uname.value == "Enter Desired Username") {
uname.focus() ;
document.getElementById("errorBox").innerHTML = "enter the username";
return false;
}
if (fname.value == "" || fname.value == "Enter name") {
fname.focus();
document.getElementById("errorBox").innerHTML = "enter the first name";
return false;
}
if (fpassword.value == "" || fpassword.value == "Select Password" ) {
fpassword.focus();
document.getElementById("errorBox").innerHTML = "enter the password";
return false;
}
if (cfpassword.value != fpassword.value) {
cfpassword.focus();
document.getElementById("errorBox").innerHTML = "doesnt match";
return false;
}
if (fname.value != '' && fpassword.value != '' && cfpassword.value != '' && uname.value != '') {
document.getElementById("errorBox").innerHTML = "form submitted successfully";
}
return true;
}
Updated - Thanks Useless Code for the helpful suggestion, I have modified the code accordingly to use onSubmit instead of the onClick event.
Your HTML code should be:
<form align="center" method="POST" action="TARGET-PAGE-TO-HANDLE-DATA" name="regform" onsubmit="return Submit();">
The action attribute specifies the target page to handle the form data. And the onSubmit attribute specifies the Javascript function to be executed when the submit button in the form is clicked.
As already stated in a comment, onsubmit is much more appropriate in this situation. The JavaScript placed in an onclick attribute will fire when the HTML element is clicked, but for a form you actually want code that executes on submission. So:
<form align="center" method="POST" action="self" name="regform" onsubmit="Submit()">
would be closer. However, it's generally considered poor practice to use the "on" attributes to handle events in JavaScript. For one, it mixes your JavaScript with your semantic HTML, which can be make debugging harder an mixes separate concerns. But it also means that whatever you use in the "on" attributes has to be in the global scope, which can become problematic fast. Consider if you had multiple forms on the page; how would you designate the submit functions for each?
A more solid way of performing this is to put your function in an event listener, e.g.:
function Submit() {
// rest of your code here
}
document.form.regform.addEventListener('submit', Submit, false);
Here the addEventListener method takes an event type string first and a function to execute when that event occurs second. The MDN article on addEventListener has more.

validation in javascript - remove the error msg on focus

i'm not very well-versed with javascript, so please bear with me.
i've a form in which i validate the controls with javascript. the error is displayed when the fields are empty via a div, but when i focus and type something in the textbox, the div should go away. but the error div doesn't and even if i type something valid, it still displays the div.
i'd like to know where am i going wrong with this script:
<script type="text/javascript">
var err = document.getElementById("errmsg");
function checkInput(inPut) {
if (inPut.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
inPut.focus();
return false;
}
else {
return true;
}
}
function checkTextBox(textBox)
{
if (textBox.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
textBox.focus();
return false;
}
else if (!checkValidity(textBox.getValue())) {
err.setStyle('display', 'block');
err.setTextValue("Please enter a valid email address!");
textBox.focus();
return false;
}
else {
return true;
}
}
. . .
<div id="errmsg" class="invalid" style="display:none;"></div> <br />
. . .
<input type="text" tabindex="1" name="name" id="name" class="input_contact" onblur="checkInput(this);"/> <br />
. . .
<input type="text" tabindex="2" name="email" id="email" class="input_contact" onblur="checkTextBox(this);"/> <br />
it's a form in facebook app but while the fbjs works, i assume there's a problem with my basic javascript.
try this
var err = document.getElementById("errmsg");
function checkInput(inPut) {
if (inPut.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
inPut.focus();
return false;
}
else {
err.setStyle('display', 'none');
err.setTextValue("");
return true;
}
}
function checkTextBox(textBox)
{
if (textBox.getValue() == "") {
err.setStyle('display', 'block');
err.setTextValue("Field cannot be empty!");
textBox.focus();
return false;
}
else if (!checkValidity(textBox.getValue())) {
err.setStyle('display', 'block');
err.setTextValue("Please enter a valid email address!");
textBox.focus();
return false;
}
else {
err.setStyle('display', 'none');
err.setTextValue("");
return true;
}
}
To get the div to disappear when you first type something, instead of when the field is checked, you'll also need onchange and/or onfocus event handlers for the fields:
<input type="text" tabindex="1" name="name" id="name" class="input_contact"
onblur="checkInput(this);"
onfocus="err.setStyle('display', 'none');"
onchange="err.setStyle('display', 'none');"
/>
They could also be set inside checkInput(), if you so desire.

Categories