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();
}
});
Related
First, I have to validate that id and password textboxes are not empty(That one's working). Then I have to validate on the same form that id on textbox needs to be a number and also a number between 3000 and 3999 (That one doesn't work). Any ideas on what's wrong with my code?
function validatefunctions() {
if (document.getElementById('idtb').value === '') {
alert('You need to enter a Customer ID');
return false;
}
if (document.getElementById('pwtb').value === '') {
alert('Please enter your password');
return false;
}
var custID;
custID = document.getElementsByName("idtb").valueOf();
if (custID !== isNan) {
alert("Customer ID needs to be numeric");
return false;
}
if (custID < 3000) {
alert("ID must be above 3000");
return false;
}
if (custID > 3999) {
alert("ID must be below 3999");
return false;
}
}
function validatefunctions() {
if (document.getElementById('idtb').value === '') {
alert('You need to enter a Customer ID');
return false;
}
if (document.getElementById('pwtb').value === '') {
alert('Please enter your password');
return false;
}
var custID = document.getElementById('idtb').value;
if (Number.isNaN(parseInt(custID))) {
alert("Customer ID needs to be numeric");
return false;
}
if (parseInt(custID) < 3000) {
alert("ID must be above 3000");
return false;
}
if (parseInt(custID) > 3999) {
alert("ID must be below 3999");
return false;
}
}
<!DOCTYPE html>
<html>
<body>
<form action="#" onsubmit="return validatefunctions()" method="post">
Customer ID: <input type="text" name="idtb" id="idtb"><br /><br />
Password: <input type="text" name="pwtb" id="pwtb"><br /><br />
<input type="submit" value="Submit">
</form>
</body>
</html>
textbox needs to be a number and also a number between 3000 and 3999 (That one doesn't work)
Why don't use input type number specifying the min and max attribute:
<form>
<input type="number" name="quantity" min="3000" max="3999" value="3000">
<input type="submit">
</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('');
}
});
});
I have three textfields namely :
State Code
Country Code
Telephone number
The value of StateCode and Country code is set by default.
If the Telephone Number textfield is entered, I want the other two fields to be made mandatory.
If the Telephone Number is empty then it is not required. How can I do this ?
I create this fiddle:
html
<label id="lblStateCode">State Code</label>
<input type="text" id="stateCode" value="585" />
<label id="lblCountryCode">Country Code</label>
<input type="text" id="countryCode" value="552" />
<label id="lblPhone">Phone</label>
<input type="text" id="phone" />
js
$("#phone, #stateCode, #countryCode").on("blur",function(){
if($("#phone").val() != ""){
if($("#stateCode").val() == ""){
$("#lblStateCode").addClass("errorClass");
}
else{
$("#lblStateCode").removeClass("errorClass");
}
if($("#countryCode").val() == ""){
$("#lblCountryCode").addClass("errorClass");
}
else{
$("#lblCountryCode").removeClass("errorClass");
}
}
else{
$("#lblStateCode").removeClass("errorClass");
$("#lblCountryCode").removeClass("errorClass");
}
});
$(function(){
if($("#phone").val() != ""){
if($("#stateCode").val() == ""){
$("#lblStateCode").addClass("errorClass");
}
else{
$("#lblStateCode").removeClass("errorClass");
}
if($("#countryCode").val() == ""){
$("#lblCountryCode").addClass("errorClass");
}
else{
$("#lblCountryCode").removeClass("errorClass");
}
}
else{
$("#lblStateCode").removeClass("errorClass");
$("#lblCountryCode").removeClass("errorClass");
}
});
css
.errorClass{
color:red;
}
fiddle
u need to apply jquery validations:
$("#form").validate({
rules: {
State: { required: function () {
if ($('#Telephone').val() != '') return true;
else return false;
},
Country: { required: function () {
if ($('#Telephone').val() != '') return true;
else return false;
}
}
messages: {
State: { required: "error messge" },
Country: { required: "error messge" }
}
});
How could I delay window.open from going to the link until all fields required on the form is filled out?
you can see Here the form.
Here is a look at the form setup:
<div name="loan-form" class="loan-form">
<div class="required-notice"><br />
</div>
<div class="loan-form-body">
<label>First Name:<span class="required-star">*</span></label>
<input type="text" name="FirstName" id="firstname" class="validate required" />
<label>Last Name:<span class="required-star">*</span></label>
<input type="text" name="LastName" id="lastname" />
<label>Email Address:<span class="required-star">*</span></label>
<input type="text" name="EmailAddress" id="emailaddress" class="validate required" />
<label>Address:<span class="required-star">*</span></label>
<input type="text" name="HomeAddress" id="HomeAddress" class="validate required" />
<label>Work Phone:</label>
<input type="text" name="DaytimePhone" id="daytimephone" />
<input type="submit" onclick="return validate();" class="button" data-form-type="submit" value="Get An Instant Report" />
</div>
</div>
this is the script I am currently using for onclick function:
function validate()
{
$('#HomeAddress').cleartitlelabel();
var address = $('#HomeAddress').val();
if (address == undefined)
address = '';
window.open('/tools/marketvalue.aspx?address=' + address);
var frm = document.forms['homevalueform'];
if (frm.EmailAddress.value == "")
{
alert("Please make sure you have completed all required fields.");
frm.EmailAddress.focus();
return (false);
}
if (frm.LastName.value == "")
{
alert("Please make sure you have completed all required fields.");
frm.LastName.focus();
return (false);
}
if (frm.FirstName.value == "")
{
alert("Please make sure you have completed all required fields.");
frm.FirstName.focus();
return (false);
}
if (frm.HomeAddress.value == "")
{
alert("Please make sure you have completed all required fields.");
frm.HomeAddress.focus();
return (false);
}
return true;
}
Sadly I could not get it to work.
Maybe I did not follow correctly but this is what I gathered:
function validate()
{
var isValid = false;
var frm = document.forms['homevalueform'];
if (frm.EmailAddress.value == "")
{
alert("Please make sure you have completed all required fields.");
frm.EmailAddress.focus();
return false;
}
if (frm.LastName.value == "")
{
alert("Please make sure you have completed all required fields.");
frm.LastName.focus();
return false;
}
if (frm.FirstName.value == "")
{
alert("Please make sure you have completed all required fields.");
frm.FirstName.focus();
return false;
}
if (frm.HomeAddress.value == "")
{
alert("Please make sure you have completed all required fields.");
frm.HomeAddress.focus();
return false;
}
$('#HomeAddress').cleartitlelabel();
var address = $('#HomeAddress').val();
if (address == undefined)
address = '';
if( isValid ){
window.open('/tools/marketvalue.aspx?address=' + address);
return true;
}else{
return false;
}
}
First: there is no need to wrap return (false); you can simply do return false;
Second:
you can setup a flag at the top of your function to false and if all elements pass your validation, set it to true.
At the end of the function, check if the flag is true and if so, call your window.open
ie. (inside your validation function)
UPDATED
function validate() {
var isValid = true;
var frm = document.forms['homevalueform'];
if (frm.EmailAddress.value == "") {
alert("Please make sure you have completed all required fields.");
frm.EmailAddress.focus();
isValid = false;
}
if (frm.LastName.value == "") {
alert("Please make sure you have completed all required fields.");
frm.LastName.focus();
isValid = false;
}
if (frm.FirstName.value == "") {
alert("Please make sure you have completed all required fields.");
frm.FirstName.focus();
isValid = false;
}
if (frm.HomeAddress.value == "") {
alert("Please make sure you have completed all required fields.");
frm.HomeAddress.focus();
isValid = false;
}
$('#HomeAddress').cleartitlelabel();
var address = $('#HomeAddress').val();
if (address == undefined){
address = '';
}
if (isValid) {
window.open('/tools/marketvalue.aspx?address=' + address);
return true;
} else {
return false;
}
}
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.