Javascript multiple fields validating - javascript

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>

Related

Triggoring Form focus with logic to another field [duplicate]

I am unable to stop the form from submitting when any of the inputs are blank. It's not erroring out, but it's also not stopping the submit. I have the function being called in the form submit input. It is under the onClick call.
JS File
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML File
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
Edit
Use the required attribute and you won't even need any JavaScript. See demo 2. for a functioning demo see this PLUNKER
OLD
Before each return false add e.preventDefault()
Demo (Does not function due to SO security measures)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
Demo 2 Use the required attribute
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
I was able to see where you doing the mistake, document.getElementById() takes in a string as the parameter but you happen to be passing an undefined variable
function stopSubmit(){
var inDay = document.getElementById('indate').value;
var inType = document.getElementById('intype').value;
var inAmount = document.getElementById('inamount').value;
if (inDay === "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount === ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}

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('');
}
});
});

The below jsp file doesn't validate from radio button onwards

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Validation Form</title>
<script type="text/javascript">
function validate()
{
var name_str=document.my_form.name.value;
if((name_str==null)||(name_str==""))
{
alert("Enter Name")
return false
}
var pwd_str=document.my_form.pwd.value;
if((pwd_str=="null")||(pwd_str==""))
{
alert("Enter Password")
return false
}
var repwd_str=document.my_form.repwd.value;
if((repwd_str=="null")||(repwd_str==""))
{
alert("ReEnter Password")
return false
}
if(pwd_str!=repwd_str)
{
alert("password must be same!");
return false
}
var age_str=document.my_form.age.value;
if((age_str=="null")||(age_str==""))
{
alert("enter age")
return false
}
if (isNaN(age_str))
{
alert("only numeric")
return false
}
var ph_str=document.my_form.ph.value;
if((ph_str=="null")||(ph_str==""))
{
alert("enter phone number")
return false
}
if (isNaN(ph_str))
{
alert("only numeric ph")
return false
}
if((ph_str.length<1)||(ph_str.length>10))
{
alert("Invalid length of ph")
return false
}
var email_str=document.my_form.email.value;
if((email_str=="null")||(email_str==""))
{
alert("enter email")
return false
}
var atposition=email_str.indexOf("#");
var dotposition=email_str.lastIndexOf(".");
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
{
alert("Please enter a valid e-mail address")
return false
}
if ((!document.getElementById("a").checked)&&(!document.getElementById("b").checked))
{
alert("no button is selected");
return false
}
var i;
var group1 = document.my_form.hobby;
for (var i=0; i<group1.length; i++) {
if (group1[i].checked)
break;
}
if (i==group1.length)
return alert("No box is checked");
var group2 = document.getElementById.dd;
var index_opt = group2.options[group2.selectedIndex].value;
if(index_opt==Select)
{
alert("select course")
return false
}
}
</script>
</head>
<body bgcolor=aqua>
<center><h3>Application Form</h3></center>
<form name="my_form" onsubmit="validate()">
<strong>Name:&nbsp&nbsp&nbsp</strong>
<input type=text name=name><br/>
<strong>Password:&nbsp&nbsp&nbsp</strong>
<input type=password name=pwd><br/>
<strong>Retype Password:&nbsp&nbsp&nbsp</strong>
<input type=password name=repwd><br/>
<strong>Age:&nbsp&nbsp&nbsp&nbsp</strong>
<input type=text name=age><br/>
<strong>Phone No:&nbsp&nbsp&nbsp&nbsp</strong>
<input tupe= text name=ph><br/>
<strong>Email:&nbsp&nbsp&nbsp&nbsp</strong>
<input type=text name=email><br/><br/>
<strong>Sex:&nbsp&nbsp&nbsp&nbsp</strong>
<input type= "radio" name="gender" id="a" value="Male">Male&nbsp&nbsp&nbsp&nbsp
<input type= "radio" name="gender" id="b" value="Female">Female&nbsp&nbsp&nbsp&nbsp<br/><br/><br/>
<strong>Hobby:</strong>
<input type="checkbox"name= "hobby" id="1" value="singning">Singning<br/>
<input type="checkbox"name= "hobby" id="2" value="reading">Reading<br/>
<input type="checkbox"name= "hobby" id="3" value="tv">TV<br/>
<br/>
<strong>Country</strong>
<select name="mymenu" id="dd">
<option value ="Select">Select</option>
<option value ="India">India</option>
<option value ="China">China</option>
<option value ="SriLanka">SriLanka</option>
</select>
<input type="submit" value=Submit>
<input type="reset" value=Reset><br/>
</form>
</body>
</html>
The code doesn't validate from the radio button on wards. but if i run the radio button code and the other validation codes after the radio button code it works and when compiled in a single form it doesn't works. the drop down menu validation doesn't works at all. please help me. Thanks in advance.
It's not a problem with your radio button check. In your code, you can use one variable like x, that's the problem. kindly refer below code :
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length)
That above code x variable doesn't declare and doesn't assign any where in your code. So that line error occurred and terminated.
You change this x to email_str, As per your code should be like below,
if (atposition<1 || dotposition<atposition+2 || dotposition+2>=email_str.length)
It's working fine.
First of all you should change your on submit Event like below
<form name="my_form" onsubmit="return validate(this.form)">
Here your complete Javascript
<script type="text/javascript">
function validate(form)
{
var name_str=document.my_form.name.value;
if((name_str==null)||(name_str==""))
{
alert("Enter Name")
return false
}
var pwd_str=document.my_form.pwd.value;
if((pwd_str=="null")||(pwd_str==""))
{
alert("Enter Password")
return false
}
var repwd_str=document.my_form.repwd.value;
if((repwd_str=="null")||(repwd_str==""))
{
alert("ReEnter Password")
return false
}
if(pwd_str!=repwd_str)
{
alert("password must be same!");
return false
}
var age_str=document.my_form.age.value;
if((age_str=="null")||(age_str==""))
{
alert("enter age")
return false
}
if (isNaN(age_str))
{
alert("only numeric")
return false
}
var ph_str=document.my_form.ph.value;
if((ph_str=="null")||(ph_str==""))
{
alert("enter phone number")
return false
}
if (isNaN(ph_str))
{
alert("only numeric ph")
return false
}
if((ph_str.length<1)||(ph_str.length>10))
{
alert("Invalid length of ph")
return false
}
var email_str=document.my_form.email.value;
if((email_str=="null")||(email_str==""))
{
alert("enter email")
return false
}
var email = document.getElementById('mail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!filter.test(email.value)) {
alert('Please provide a valid email address');
email.focus;
return false;
}
var gender=document.my_form.gender.value;
if((gender=="null")||(gender=="")){
alert("Please Select Gender");
return false;
}
var i;
var group1 = document.my_form.hobby;
for (var i=0; i<group1.length; i++) {
if (group1[i].checked)
break;
}
if (i==group1.length){
alert("No box is checked");
return false;
}
var country=document.my_form.mymenu.value;
if(country=='Select'){
alert("You must Select your Country");
return false;
}
}
</script>

Javascript form validation needs fix

I'm trying to make a basic form validation but it's not working. I need to make it in such a way that after validation is passed, THEN ONLY it submits the form. I'm not sure how to do it though. My code is below.
[Important request]
** I'm actually pretty new to this so if possible I would like to get some concrete information/explanation concerning the DOM and how to manipulate it and style it (W3School is NOT helping) **
<form id="reg" method="POST" action="user.php" onsubmit="return validate()">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="submit">Register</button>
</form>
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else{
return true;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
Thanks
Try this:
function validate() {
var validForm = true;
var msg = '';
if (document.getElementById('first').value == "") {
msg += 'First Name Blank! ';
validForm = false;
}
if (document.getElementById('last').value == "") {
msg += 'Last Name Blank! ';
validForm = false;
}
if (!validForm) {
alert(msg);
}
return validForm;
}
Plunker example
Your validation function only validates the first name. Whether it's valid or not, the function returns before checking the last name.
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false; // WILL RETURN EITHER HERE ...
}else{
return true; // ... OR HERE
}
The return statement will exit the function at the point it appears, and other code after that is simply not executed at all.
Instead of doing it that way, keep a flag that determines whether the fields are all OK:
function validate(){
var isValid = true; // Assume it is valid
if(document.getElementById('first').value = ""){
alert('First Name Blank!');
isValid = false;
}
if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
isValid = false;
}
return isValid;
}
Here's the code to check for validation and stop it from submitting if it is incorrect data.
<form id="reg" method="POST" action="user.php">
<label for="first">First Name: </label>
<input id="first" name="first" type="text" value="">
<label for="last">Last Name: </label>
<input id="last" name="last" type="text" value="">
<button type="button" id="submit">Register</button>
</form>
document.getElementById('submit').onclick = function(){
if(validate()){
document.getElementById('reg').submit();
}
}
function validate(){
if(document.getElementById('first').value == ""){
alert('First Name Blank!');
return false;
}else if(document.getElementById('last').value == ""){
alert('Last Name Blank!');
return false;
}else{
return true;
}
}
All I have done here is made the submit button a regular button and handled submitting via JS, When an input of type submit is clicked the page will submit the form no matter what. To bypass this you can make it a regular button and make it manually submit the form if certain conditions are met.
Your javascript code can be:
document.getElementById('submit').onclick = function () {
if (validate()) {
document.getElementById('reg').submit();
}
}
function validate() {
if (document.getElementById('first').value == "") {
alert('First Name Blank!');
return false;
} else if (document.getElementById('last').value == "") {
alert('Last Name Blank!');
return false;
} else {
return true;
}
}

Categories