javascript checking for blank for phonenumber and address - javascript

Please help me, I'm stuck.
Why doesn't the JavaScript below work? The script is checking if phone number and address is empty, but when the phone number and address field is entered, the alert still pops out.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
const phone = document.getElementById("phoneNumberInput").value;
const address = document.getElementById("addressInput").value;
function checkingIsEmpty() {
if (phone == ''){
alert("Please insert your phone number");
return false;
}
if (address ==''){
alert("Please insert your address");
return false;
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>

I'd agree with #Madara's comment, that you should... just add required attribute on form inputs which are required and let the browser do the work for you
However, I believe the reason your code is not working is because you appear to be setting the const values of phone and address on entry to the screen... and then you're checking that initial value (rather than the latest value).
Instead you need to get the latest value from the controls as part of the function...
function checkingIsEmpty(){
if (document.getElementById("phoneNumberInput").value == ''){
alert("Please insert your phone number");
return false;
}
if (document.getElementById("addressInput").value ==''){
alert("Please insert your address");
return false;
}
return true;
}
(Minor edit, you also need to return true at the end of your function, otherwise your submit won't work)

simplest way is to check if (!phoneInput.value) { ... }
as empty string and null will return falsy value

The problem you are having is because you are assigning the value of the fields at the time the page loads. Not at the time the function is called on submit. If you move the variable assignment into the function it should work for you.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
function checkingIsEmpty(){
const phone = document.getElementById("phoneNumberInput").value;
const address = document.getElementById("addressInput").value;
if (phone == ''){
alert("Please insert your phone number");
return false;
}
if (address ==''){
alert("Please insert your address");
return false;
}
return false;//for the example I don't want it to submit
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>

You need to include the document.getElementById in your conditionals. Also, I would wrap both conditionals (Phone and Address) in another conditional so you can add classes for error styling on errored fields.
const order = document.getElementById("orderInput");
const main = document.getElementById("main");
var phone = document.getElementById("phoneNumberInput").value;
var address = document.getElementById("addressInput").value;
function checkingIsEmpty(){
if (document.getElementById("phoneNumberInput").value == '' || document.getElementById("addressInput").value == '') {
if (document.getElementById("phoneNumberInput").value == ''){
alert("Please insert your phone number");
return false;
}
if (document.getElementById("addressInput").value == ''){
alert("Please insert your address");
return false;
}
} else {
alert('success');
}
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>

The values of inputs are stored inside a constant, not a variable.
When page is loaded, the script is executed and the contents of actual inputs are stored.
When you're calling checkingIsEmpty() the values aren't refreshed.
I suggest you to get the value inside the checkingIsEmpty() function if you want to keep checking with javascript, but as suggested Madara in comments, you can use the required attribute <input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber" required>.
Checking inputs with required attribute or javascript is nice, but you have to check it server-side too. It's easy to press F12 and edit dom.
function checkingIsEmpty()
{
let phone = document.getElementById("phoneNumberInput").value;
let address = document.getElementById("addressInput").value;
if (phone == '')
{
alert("Please insert your phone number");
return (false);
}
if (address == '')
{
alert("Please insert your address");
return (false);
}
return (true); //You forgot to return true in case of your form is validated
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>checking form is empty</title>
</head>
<body>
<form class="" action="index.html" method="post" onsubmit="return checkingIsEmpty()">
<div id="message">
<label>
<textarea name="messageInput" rows="2" cols="40" placeholder="add message..."></textarea>
</label>
</div>
<div id="phoneNumber">
<input id="phoneNumberInput" type="number" name="phone" value="" placeholder="Please input your phonenumber">
</div>
<div id="address">
<input id="addressInput" type="text" name="address" placeholder="your address here" size= "50px" value="" >
</div>
<div id="order">
<input id="orderInput" type="submit" name="description" value="order" min='0'> <p></p>
</div>
<div id= "reset">
<input type="reset" name="" value="RESET">
</div>
</form>
<script src="app.js" charset="utf-8"></script>
</body>
</html>

Related

If statement not executing properly and not showing from where error is coming?

My html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title> Registration Form</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<form method="">
<div class="input-1 input-box">
<label for="name">First Name :-</label>
<input type="text" id="name" name="Fname" required>
</div>
<div class="input-3 input-box">
<label for="Password">Password :-</label>
<input type="password" name="password" id="Password" required>
</div>
<div class="input-2 input-box">
<label for="father">Company :-</label>
<input type="text" name="Mname" id="Company" required>
</div>
<div class="input-4 input-box">
<label for="CTC">CTC :-</label>
<input type="Text" id="CTC" name="CTC" min="0" required>
</div>
<div class="input-4 input-box">
<label for="age">Age :-</label>
<input type="Text" id="Age" name="age" min="1" required>
</div>
<div class="input-4 input-box">
<label for="Clg">College :-</label>
<input type="Text" id="Clg" name="Clg" min="1" required>
</div>
<div class="input-5 input-box">
<label for="Gender">Gender :-</label>
<input type="text" id="Gender" name="Gender">
</div>
<div class="input-6">
<input type="submit" value="Submit" class="btn-1 btn" onclick='checkUser();'>
<input type="reset" value="Reset" class="btn-2 btn">
</div>
<script src="validation.js"></script>
</form>
</div>
<script src="validation.js"></script>
</body>
</html>
and my JavaScript , the first six condition are giving me correct result but the 7th condition not redirecting the given page
function checkUser() {
var FirstName = document.getElementById("name").value;
var UserPass = document.getElementById("Password").value;
var compName = document.getElementById("Company").value;
var UserCtc = document.getElementById("CTC").value;
var ClgName = document.getElementById("Clg").value;
var User_Gender = document.getElementById("Gender").value;
let Age_User = document.getElementById("Age").value;
// ------------------user-database----------------------------
var n = "Rahul";
var pass = "Rahul123";
var cmp = "TCS";
var ctc = "12LPA";
var date = "25years";
var clgn = "IIT";
var gen = "M";
if (
FirstName === n &&
UserPass === pass &&
compName === cmp &&
UserCtc === ctc &&
ClgName === clgn &&
User_Gender === gen &&
Age_User === date
) {
alert("Welcome back");
} else {
alert("wrong info");
}
}
I'm trying to give some form validation but not getting expected results , I'm trying to get error alert if user put wrong information and if not , then redirect some other page if user put right information .

how do i make a verifier for my html form?

<div class="entry-container row">
<div class="signup containerss col">
<h1 class="center">New Here,</h1>
<h3 class="center">Signup Here</h3>
<form action="signup" class="form-inside" method='post'>
username<input type='text' name='Username' required/><br>
password<input type="text" name='Password' required/><br>
Firstname<input type="text" name='Fname' required/><br>
Lastname<input type="text" name='Lname' required/><br>
Date Of Birth<br><input type="date" name='DOB' required/><br>
Email<input type="text" name='Email' required/><br>
<input type='submit' name='Submit'/>
</form>
</div>
<div class="login float-right col" style="height: 300px;">
<h1 class="center">Already a Member</h1>
<h3 class="center">Login Here</h3>
<form action="login" class="form-inside" method='POST'>
username<input type='text' name='User' required/><br>
password<input type='text' name='Pass' required/>
<input type="submit" name='submit'>
</form>
</div>
<div>
here is a simple form for login or signup,
now what I want to do is i want to make a js code that verifies if the username is a string(has no special chars), password is strong enough, email is valid etc, and if everything is perfect ,only then the user must be allowed to submit the form,
if not then I want to tell the mistakes yo the user, while the user is typing
how can I achieve this.
2 question i want answer to ,
1
I had tried this,
<div class='hide' onclick='showerror()' id='error'>error</div>
<style>.hide{display:none;}</style>
<script>function showerror(){
var error= document.getelementbyid('error')
error.Classlist.toggle('hide')
}</script>
how can i call this same function when the user is typing ,
2
how can i use regex in js to verify if the textontext of a element is string or not.
You can use javascript event for validating form.
function ValidateForm()
{
var inputText1 = document.form1.text1;
var inputText2 = document.form1.text2;
var inputText3 = document.form1.text3;
//add other elements validation here
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/;
if(inputText.value.match(mailformat))
{
document.form1.text1.focus();
return true;
}
else
{
alert("You have entered an invalid email address!");
document.form1.text1.focus();
return false;
}
}
HTML
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript form validation - checking email</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input an email and Submit</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li><input type='password' name='text2'/></li>
<li><input type='text' name='text3'/></li>
<li> </li>
<li class="submit"><input type="submit" name="submit" value="Submit" onclick="ValidateForm()"/></li>
<li> </li>
</ul>
</form>
</div>
<script src="email-validation.js"></script>

Javascript Keyup Form

How would one display an incorrect or correct words beside a form in any colour beside the field box when typing? I'm trying to make it so it gives me a real time correct and incorrect when I type in values that match the JS rule.
It should give a real time correct or incorrect beside the box and if it matches the rule then it displays correct
My HTML:
<!doctype html>
<html lang="en">
<head>
<title> Form Example </title>
<meta charset="utf-8">
<link href="keyupform.css" rel="stylesheet">
<script src="prototype.js"></script>
<script src="formkeyup.js"></script>
</head>
<body>
<div class="box" >
<form id="myForm" action="http://www.eecs.yorku.ca/~mbrown/EECS1012/testForm.php" method="get">
<!-- user id -->
<h2> Enter Info </h2>
<p> <span class="fieldName">UserID: </span>
<input type="text" id="userid" name="userid" class="input">
<span class="message"></span></p>
<!-- -->
<p style="text-align:center" class="types"> Enter Code: EECS, ESSE, MUTH, HIST, CHAP, BIO </p>
<p> <span class="fieldName"> Codes </span>
<input type="text" id="code" name="code" class="input">
<span class="message"></span></p>
<!-- Number -->
<p> <span class="fieldName"> Course Num (XXXX): </span>
<input style="width: 4em;" id="number" type="text" name="number" class="input">
<span class="message"></span></p>
<hr>
<p style="text-align:center;"> <button id="submitButton" type="button" onclick="submitbtn"> Submit </button> <input id="clear" type="reset" value="Clear"> </p>
<p style="text-align:center;" id="formError"> <p>
</form>
</div>
</body>
</html>
JS:
window.onload = function() {
$("userid").observe("keyup", enforceID);
$("code").observe("keyup", enforcecode);
$("number").observe("keyup", enforcenumbers);
$("submitButton").observe("click", submitbtn);
}
function enforceID() {
// fucntion must start with a letter and can be any number or letter after
var re = /^[A-Z][A-Z][0-9]+/i;
}
function enforcecode() {
// Only can use these Codes
var codes = ["EECS", "ESSE", "MUTH", "HIST", "CHAP", "BIO"];
var codeType = $("codeType").value;
codeType = codeType.toUpperCase();
}
function enforcenumbers() {
//Only 4 numbers allowed
var re = /^[0 -9][0 -9][0 -9][0 -9]$/
}
You can trigger the form validation on keydown event.
const form = document.getElementById('form');
document.getElementById('userid').addEventListener('keydown', event => {
form.reportValidity();
}, false);
document.getElementById('code').addEventListener('keydown', event => {
form.reportValidity();
}, false);
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Title</title>
</head>
<body>
<form id="form">
<label for="userid">User ID:</label>
<input type="text" id="userid" name="userid" pattern="[A-Z]{2}\d+">
<br />
<label for="code">Code:</label>
<input type="text" id="code" pattern="EECS|ESSE|MUTH|HIST|CHAP|BIO" />
</form>
</body>
</html>

form validation in bootstrap 3

I have a form in bootstrap 3. I am able to do basic validation with the has-error class. How do l check for specific user inputs like?
The user can only enter characters as first name and last name
The user can only enter numbers /digits as telephone number
The user can only enter valid email characters.
And also how can l output a more user friendly validation error messages.
I'm new to bootstrap and any help is greatly appreciated. Here is my code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link href="css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<form method="post" id="contactform" action="" role="form">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="First Name" name="firstname" type="text" id="firstname" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="Last Name" name="lastname" type="text" id="lastname" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-envelope"></span></span>
<input class="form-control" placeholder="Email" name="email" type="text" id="email" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-earphone"></span></span>
<input class="form-control" placeholder="Phone Number" name="phone" type="text" id="phone" />
</div>
</div>
<button type="button" id="contactbtn" class="btn btn-
primary">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
function validateText(id) {
if ($("#" + id).val() == null || $("#" + id).val() == "") {
var div = $("#" + id).closest("div");
div.addClass("has-error");
return false;
} else {
var div = $("#" + id).closest("div");
div.removeClass("has-error");
return true;
}
}
$(document).ready(
function() {
$("#contactbtn").click(function() {
if (!validateText("firstname")) {
return false;
}
if (!validateText("lastname")) {
return false;
}
if (!validateText("email")) {
return false;
}
if (!validateText("phone")) {
return false;
}
$("form#contactform").submit();
});
}
);
</script>
</body>
</html>
HTML input fields have an attribute called pattern which you can use for ensuring a specific input with a regex.
<input class="form-control" placeholder="First Name"
name="firstname" type="text" id="firstname" pattern="^\w*$" />
...
<input class="form-control" placeholder="Last Name" name="lastname"
type="text" id="lastname" pattern="^\w*$" />
...
<input class="form-control" placeholder="Email" name="email"
type="text" id="email" pattern="^[^#\\s]+#[^#\\s]+\\.[^#\\s]+$" />
...
<input class="form-control" placeholder="Phone Number" name="phone"
type="text" id="phone" pattern="^\d*$" />
That's just a simple sample e-mail regex. There are lot of other regex for e-mails.
You can use jquery boostrap validation.It's much easy.you can follow following
answer
A combination of using the correct input type as well as declaring a pattern attribute can likely preclude the need for any special JavaScript.
1) The user can only enter characters as first name and last name
For this you need to rely on <input type="text"> which by default allows basically anything. So we'll need to apply a pattern that restricts this field to only letters:
<input type="text" pattern="[A-Za-z]+">
2) The user can only enter numbers /digits as telephone number
Depending on your needs this could be as simple as using the correct input type:
<input type="tel">
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/tel
Because different countries have different patterns you may want to improve this with the addition of a pattern attribute.
<input type="tel" pattern="^[0-9\-\+\s\(\)]*$">
This will allow your number inputs to be a bit more flexible, accept dashes and parenthesis, allow the user to specify a +DIGIT country code, etc.
3) The user can only enter valid email characters.
Again using the correct input type will greatly simplify your validation efforts:
<input type="email">
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email
This is another one that can be a little 'fuzzy' when you're comparing certain input types as it really just looks for handle#domain.extension. You can read more about its specific validation patterns using the above link to Mozilla's developer toolkit.
You might have to tweak things if you want to use something else. But this is preferably used in bootstrap way.
var showErrorSuccess = function(element, status) {
if (status === false) {
element.parent().next().removeClass('hidden').parent().addClass('has-error');
return false;
}
element.parent().next().addClass('hidden').parent().removeClass('has-error').addClass('has-success');
};
var validate = function() {
event.preventDefault();
//validate name
var name = $('#firstname').val();
if (name.length < 3) {
return showErrorSuccess($('#firstname'), false);
}
showErrorSuccess($('#firstname'));
var lastname = $('#lastname').val();
if (lastname.length < 3) {
return showErrorSuccess($('#lastname'), false);
}
showErrorSuccess($('#lastname'));
//validate email
var email = $('#email').val(),
emailReg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
if (!emailReg.test(email) || email == '') {
return showErrorSuccess($('#email'), false);
}
showErrorSuccess($('#email'));
//validate phone
var phone = $('#phone').val(),
intRegex = /[0-9 -()+]+$/;
if ((phone.length < 6) || (!intRegex.test(phone))) {
return showErrorSuccess($('#phone'), false);
}
showErrorSuccess($('#phone'));
};
body>form {
padding-left: 15px;
padding-top: 15px;
padding-right: 15px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form class="form-vertical" method="post" id="contactform" onSubmit="javascript:validate()" action="" role="form">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="First Name" name="firstname" type="text" id="firstname" />
</div>
<p class="help-block hidden">Please enter a name 3 characters or more.</p>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="Last Name" name="lastname" type="text" id="lastname" />
</div>
<p class="help-block hidden">Please enter a name 3 characters or more.</p>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-envelope"></span></span>
<input class="form-control" name="email" placeholder="Email" type="email" id="email" />
</div>
<p class="help-block hidden">Please enter a valid email address.</p>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-earphone"></span></span>
<input class="form-control" name="phone" placeholder="Phone Number" type="phone" id="phone" />
</div>
<p class="help-block hidden">Please enter a valid phone number.</p>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
Here is easy and best concept to use form validation by using custom jquery/javascript code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<form method="post" id="contactform" action="" role="form">
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="First Name"
name="firstname" type="text" id="firstname" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-user"></span></span>
<input class="form-control" placeholder="Last Name" name="lastname"
type="text" id="lastname" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-envelope"></span></span>
<input class="form-control" name="email" placeholder="Email" type="email" id="email" />
</div>
</div>
<div class="form-group">
<div class="input-group">
<span class="input-group-addon transparent"><span class="glyphicon
glyphicon-earphone"></span></span>
<input class="form-control" name="phone" placeholder="Phone Number"
type="phone" id="phone" />
</div>
</div>
<button type="button" id="contactbtn" onclick="validateText();" class="btn btn-
primary">Submit</button>
</form>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function validateText(id){
//validate name
var name = $('input[id="firstname"]').val();
if (name.length < 3)
{
alert('Please enter a name 3 characters or more.');
return false;
}
var lastname = $('input[id="lastname"]').val();
if (name.length < 3)
{
alert('Please enter a name 3 characters or more.');
return false;
}
//validate email
var email = $('input[id="email"]').val(),
emailReg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/
if(!emailReg.test(email) || email == '')
{
alert('Please enter a valid email address.');
return false;
}
//validate phone
var phone = $('input[id="phone"]').val(),
intRegex = /[0-9 -()+]+$/;
if((phone.length < 6) || (!intRegex.test(phone)))
{
alert('Please enter a valid phone number.');
return false;
}
}
</script>
</body>
</html>

Validate inputs in form

How do I validate the input(name and age) below? E.g. not allowing empty inputs, maximum age from 0 to 100 and max length? I just started to look into JavaScript/JQuery today.
<form action="#">
<fieldset>
<div class="textinput">
<label for="name">Your name:</label>
<input type="text" name="name">
</div>
<div class="textinput">
<label for="name">Your age:</label>
<input type="text" name="age">
</div>
<div class="textareainput">
<label for="info">About yourself:</label>
<textarea></textarea>
</div>
<div class="action">
<button>Submit</button>
</div>
</fieldset>
</form>
I hope this not a bad question. If it is, please give me the reason for downvote so I can improve my future posts.
I think this is what you want. there are so many libraries (validations) that you can use to validate your script. but if you want do do it in your own way try this.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<form action="#">
<fieldset>
<div class="textinput">
<label for="name">Your name:</label>
<input type="text" name="name" id="nameid">
</div>
<div class="textinput">
<label for="name">Your age:</label>
<input type="text" name="age" id="ageid">
</div>
<div class="textareainput">
<label for="info">About yourself:</label>
<textarea id="textareaid"></textarea>
</div>
<h3 style="color:red;font-family:monospace;" id="warning"></h3>
<div class="action">
<input type="button" value="submit" id="click">
</div>
</fieldset>
</form>
</body>
<script type="text/javascript">
$("#click").click(function(){
$("#warning").text("");
var namefield = $("#nameid").val();
var agefield = $("#ageid").val();
var texarefield = $("#textareaid").val();
if (namefield == "" || agefield == "" || texarefield == "")
{
$("#warning").text("all field sholud be fill");
}
else if (namefield != "" && agefield != "" && texarefield != "")
{
var ageInteger = parseInt(agefield);
if (ageInteger < 0 || ageInteger > 100)
{
$("#warning").text("age should be between 0 and 100");
}
else
{
$("#warning").text("");
}
}
else
{
$("#warning").text("");
}
});
</script>
</html>
this is very basic and simple validation.hope this will help to you.
You can use https://jqueryvalidation.org/
The HTML doesn't need to be altered. See https://jqueryvalidation.org/validate/#rules

Categories

Resources