You have several errors there.
First, you have to return a value from the function in the HTML markup: <form name="ff1" method="post" onsubmit="return validateForm();">
Second, in the JSFiddle, you place the code inside onLoad which and then the form won't recognize it - and last you have to return true from the function if all validation is a success - I fixed some issues in the update:
https://jsfiddle.net/mj68cq0b/
function validateURL(url) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}
function validateForm()
{
// Validate URL
var url = $("#frurl").val();
if (validateURL(url)) { } else {
alert("Please enter a valid URL, remember including http://");
return false;
}
// Validate Title
var title = $("#frtitle").val();
if (title=="" || title==null) {
alert("Please enter only alphanumeric values for your advertisement title");
return false;
}
// Validate Email
var email = $("#fremail").val();
if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
alert("Please enter a valid email");
return false;
}
return true;
}
Answer from Adidi on Stack OverflowVideos
You have several errors there.
First, you have to return a value from the function in the HTML markup: <form name="ff1" method="post" onsubmit="return validateForm();">
Second, in the JSFiddle, you place the code inside onLoad which and then the form won't recognize it - and last you have to return true from the function if all validation is a success - I fixed some issues in the update:
https://jsfiddle.net/mj68cq0b/
function validateURL(url) {
var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
return reurl.test(url);
}
function validateForm()
{
// Validate URL
var url = $("#frurl").val();
if (validateURL(url)) { } else {
alert("Please enter a valid URL, remember including http://");
return false;
}
// Validate Title
var title = $("#frtitle").val();
if (title=="" || title==null) {
alert("Please enter only alphanumeric values for your advertisement title");
return false;
}
// Validate Email
var email = $("#fremail").val();
if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
alert("Please enter a valid email");
return false;
}
return true;
}
The simplest validation is as follows:
<form name="ff1" method="post">
<input type="email" name="email" id="fremail" placeholder="[email protected]" />
<input type="text" pattern="[a-z0-9. -]+" title="Please enter only alphanumeric characters." name="title" id="frtitle" placeholder="Title" />
<input type="url" name="url" id="frurl" placeholder="http://yourwebsite.com/" />
<input type="submit" name="Submit" value="Continue" />
</form>
It uses HTML5 attributes (like as pattern).
JavaScript: none.
So I am new to javascript and wanted to start a project where I would make a form validation thing that insured you had entered your name, email and password. Although when I started building it I realized you can just add required to all of them and when you click submit if you have not entered your info it will give a pre styled message saying to enter. Can someone explain the benefits of using javascript for this specific feature? example below
<form class="join-form">
<div class="input-group">
<label>Name:</label>
<input type="text" required>
</div>
<div class="input-group">
<label>Email:</label>
<input type="email" required>
</div>
<div class="input-group">
<label>Password:</label>
<input type="password" required>
</div>
<div class="input-group">
<button type="submit" class="btn">Join Now</button>
</div>
</form>I used a js file to check if username and password are correct for a login. The js file contains a single username and password that work and I want to know how safe it is, I use flask so I can do the validation in the backend, Is it better or is it also unsafe?
The correct username and password according to the js file:
username = "username"
password = "password"
js file:
function validateForm() {
let x = document.forms["myForm"]["username"].value;
let y = document.forms["myForm"]["password"].value;
let username = document.getElementById('errorUsername');
let password = document.getElementById('errorPassword');
if (x != "username" && y != "password") {
username.style.visibility = "visible";
password.style.visibility = "visible";
return false
}
else if (x == "username" && y != "password"){
username.style.visibility = "hidden";
password.style.visibility = "visible";
return false
}
else if (x != "username" && y == "password"){
username.style.visibility = "Password";
password.style.visibility = "hidden";
return false
}
else {
return true
}
}HTML file:
<div class="center">
<h1>login</h1>
<form action="/login" method="POST" name="myForm" onsubmit="return validateForm()">
<div class="txt_field">
<input type="text" name="username" required autocomplete="off">
<label for="username">username</label>
</div>
<small id=errorUsername>Incorrect username</small>
<div class="pass"></div>
<div class="txt_field">
<input type="password" name="password" required>
<label id=sisma for="username">password</label>
</div>
<small id=errorPassword>Incorrect password</small>
<div class="pass"></div>
<input type="submit" value="login">
<div class="signup_link"> <a href="#"></a>
</div>
</form>
</div>Python file in the backend:
@auth.route('/login', methods=['GET', 'POST'])
def login():
if request.method == "POST":
username = request.form.get("username")
session['logged_in'] = username
return redirect(url_for('views.home'))
return render_template("login.html")
You can use a table with data of fields and then just iterate over it.
var fields = [[document.getElementById("username"),"Please Enter Your Username"],
[document.getElementById("fname"), "Please Enter Your First Name"],
[document.getElementById("lname"), "Please Enter Your Last Name"]];
function Check()
{
var error = [];
for (var i in fields)
{
if (fields[i][0].value == "")
{
error.push(fields[i][1]);
fields[i][0].style.borderColor = "red";
}
}
if (error.length)
window.alert(error.join(",\n"));
return !error.length;
}
Note: probably you want o make sure that the value isnt empty so I would suggest you using something like: fields[i][0].value.replace(/\s/g, "") == "" instead.
I'd go with this way, using data-* attribute to store the error messages:
Live demo
<form id="myForm" name="myForm">
<input type="text" name="username" id="username" data-err="Please enter a username" />
<input type="text" name="fname" id="fname" data-err="Please enter a first name" />
<input type="text" name="lname" id="lname" data-err="Please enter a last name"/>
<input type="submit" />
</form>
function formValidator(){
var inputs = this.getElementsByTagName('input');
var allErrors = '';
for(var i=0; i<inputs.length; i++) {
var el = inputs[i];
var data = el.dataset.err;
if(data && el.value.trim() === ''){
allErrors += data +'\n';
}
}
if(allErrors){
alert(allErrors);
return false;
}else{
alert('All fine. Submit!');
}
}
document.myForm.onsubmit = formValidator;