Using Javascript validation checks in a Django Project - javascript

I have to make a registration page in a project that uses Django as the backend framework.. In the registration page, I have to input the names, email, password and mobile... During registration, I need to validate email if its a valid format, check if the mobile number is of 10 digits and check if the password is a strong one.. I want to do it using javascript... I have written the code for the form and also the javascript function... But while running on the server I am unable to get the desired validation checks and alerts... Please help what should i do?
signup.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
{% load static %}
<link rel="stylesheet" href="{% static 'signup1.css'%}">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register</title>
<!--Javascript form validator-->
<link rel="stylesheet" href="{% static './register.js' %}">
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="text-center">
<h1>Signup</h1>
<h6>Register yourself</h6>
</div>
<form style="text-align: top;" name="myForm" method="POST" action="" onsubmit="validate()" >
{% csrf_token %}
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label"><b>First Name</b></label>
<input type="text" name="first_name"placeholder="First Name" class="form-control" id="name" required aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label"><b>Last Name</b></label>
<input type="text" name="last_name"placeholder="Last Name" class="form-control" id="name" required aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label"><b>Mobile Number</b></label>
<input type="tel" name="mobile" class="form-control" id="number" required aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputEmail1" class="form-label"><b>Email address</b></label>
<input type="email" name="email" placeholder="Enter Email Id" class="form-control" id="email" required aria-describedby="emailHelp">
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label"><b>Password</b></label>
<input type="password" name="password" placeholder="Enter Password" class="form-control" id="password" required>
</div>
<div class="mb-3">
<label for="exampleInputPassword1" class="form-label"><b>Your Choice</b></label><br>
<input type="radio" id="user" name="user_type" value="user">
<label for="html">User</label><br>
<input type="radio" id="admin" name="user_type" value="admin">
<label for="css">Admin</label><br>
</div>
<button type="submit" class="btn btn-primary" onclick="validate()">Submit</button>
</form>
<a style="color: aqua; margin-top: 10px;" href="http://localhost:8000/"><small>Already Registered? Click to login</small></a>
</div>
</div>
</div>
</div>
</body>
</html>
register.js (In static folder of the project)
function validate()
{
var abc=document.forms["myForm"]["first_name"].value;
if(abc=="")
{
alert("Please enter the first name");
return false;
}
var def=document.forms["myForm"]["last_name"].value;
if(def=="")
{
alert("Please enter the last name");
return false;
}
var email = document.forms["myForm"]["email"].value;
var re = "/^[a-z0-9+_.-]+#[a-z0-9.-]+$"
var x=re.test(email);
if(x)
{}
else
{
alert("Email id not in correct format");
return false;
}
var mobile = document.forms["myForm"]["mobile"].value;
var check="^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$"
var a=check.test(mobile);
if(a)
{}
else
{
alert("Invalid mobile number");
return false;
}
var pass=document.forms["myForm"]["password"].value;
var checks="^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[#$!%?&])[A-Za-z\d#$!%?&]{8,}$"
var res=checks.test(pass);
if(res)
{}
else
{
alert("Password must contain atleast 1 small, 1 capital, 1 numeric, 1 special character and must be atleast 8 characters long");
return false;
}
}

Your regular expressions are formatted as strings, not regular expressions.
For example...
// re is string
var re = "/^[a-z0-9+_.-]+#[a-z0-9.-]+$"
var x=re.test(email);
// re is regex
var re = /^[a-z0-9+_.-]+#[a-z0-9.-]+$/
var x=re.test(email);

Related

javascript not working properly on 2 forms in same html page

even when the password has all the correct values !((password.match(passw)) is executing
and if i remove the formvalidationlogin.js then also the formvalidationregistartion.js is throwing error for f1 from. when the login and registartion were in seperate html pages these javascript functions worked perfectly.
<!DOCTYPE html>
<html>
<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>signup-login</title>
<link rel="stylesheet" type="text/css" href="css/index.css">
<link href="https://fonts.googleapis.com/css2?family=Jost:wght#500&display=swap" rel="stylesheet">
</head>
<body>
<div class="main">
<input type="checkbox" id="chk" aria-hidden="true">
<div class="signup">
<form name="regform" action="registrationsession.php" onsubmit="return Validate()" method="post">
<label for="chk" aria-hidden="true">Sign up</label>
<input type="text" id="username" name="username" placeholder="User name" required="">
<input type="email" id="email" name="email" placeholder="Email" required="">
<input type="password" id="password" name="password" placeholder="Password" required="">
<script type="text/javascript" src="javascript/formvalidationregistration.js"></script>
<input type="submit" name="submit" value="Sign Up" class="login-button">
</form>
</div>
<div class="login">
<form name="f1" action="loginsession.php" onsubmit="return Validate()" method="post">
<label for="chk" aria-hidden="true">Login</label>
<input type="email" name="email" id="email" placeholder="Email" required="">
<input type="password" name="pass" id="pass" placeholder="Password" required="">
<script type="text/javascript" src="javascript/formvalidationlogin.js"></script>
<input type="submit" name="submit" value="Login" class="login-button">
</form>
</div>
</div>
</body>
</html>
//formvalidationregistration.js
function Validate() {
var password = regform.password.value;
var name = regform.username.value;
var passw = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{8,}$";
if (!(password.match(passw))){
alert("Password Should Contain At Least One Uppercase Letter, One Lowercase letter, One Number And One Special Character");
return false;
}
else if(password.length < 8) {
alert("Password Must Be At least 8 Characters long");
return false;
}
else if(name.length < 6) {
alert("Username Must Be At least 6 Characters long");
return false;
}
else if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(regform.email.value))) {
alert("You have entered an invalid email address!");
return false;
}
}
//formvalidationlogin.js
function Validate() {
var password = f1.pass.value;
var passw = "^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!#$%^&*-]).{8,}$";
if (!(password.match(passw))) {
alert("Password Should Contain At Least One Uppercase Letter, One Lowercase letter, One Number And One Special Character");
return false;
}
else if (password.length < 8) {
alert("Password Must Be At least 8 Characters long");
return false;
}
}

HTML Javascript redirecting user with if statement does not work

I want to use user input to decide whether or not the user is redirected to another page. In this case, the user inputs a username and password. If the username and password is correct, then the user is redirected. For this, I use simple javascript and html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,minimum-scale=1">
<title>Login</title>
<!-- the form awesome library is used to add icons to our form -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css"> -->
<!-- include the stylesheet file -->
<link href="login.css" rel="stylesheet" type="text/css">
<script>
function testResults (form) {
var given_username = form.username.value;
var given_password = form.password.value;
var correct_username = "123";
var correct_password = "123";
if (given_username == correct_username && given_password == correct_password) {
window.location.assign("redirected.html");
}
else {
alert("Wrong username and/or password.")
}
}
</script>
</head>
<body>
<div class="login">
<h1>Login</h1>
<form action="" method="get">
<label for="username">
<!-- font awesome icon -->
<i class="fas fa-user"></i>
</label>
<input type="text" name="username" placeholder="Username" id="username" required>
<label for="password">
<i class="fas fa-lock"></i>
</label>
<input type="password" name="password" placeholder="Password" id="password" required>
<input type="submit" value="Login" onclick="testResults(this.form)" />
</form>
</div>
</body>
</html>
However, when I fill in the correct username and password, in this case '123', I don't get redirected at all. Nothing happens.
But, when I don't use an if statement at all:
<script>
function testResults (form) {
window.location.assign("redirected.html");
}
</script>
it works correctly. That is, whenever you press the submit button, you get redirected. However, in this case the user does not have to fill in credentials at all, so in my case this is not of much use.
I have tried window.location, location.assign, location.href, location.replace and variants, but all yield the same result.
How can I solve or work around this?
this.form is wrong.
also, you might consider using the onsubmit event:
<form action="" method="get" onsubmit="testResults(this); return false">
<label for="username">
<!-- font awesome icon -->
<i class="fas fa-user"></i>
</label>
<input type="text" name="username" placeholder="Username" id="username" required>
<label for="password">
<i class="fas fa-lock"></i>
</label>
<input type="password" name="password" placeholder="Password" id="password" required>
<input type="submit" value="Login" />
</form>

set focus in next html input after editing and clicking enter

I have 3 inputs in html form.
I wrote html and copied js from another topic here. But I can't understand, what I need write down for working.
For example, I need after inserting data in input with id "tLogin" and clicking Enter moving focus on next input with id "tTable", and next move focus to input with id "tOrder". After entering data to tOrder return focus to tLogin.
function keyPressFunction(e) {
const focus = $(document.activeElement); //get your active elememt ie select input
let inputView;
if (e.which === 13 || e.keyCode === 13 ) {
inputView = focus.closest('div').next().find(".field-focus"); // go to tbody and search for next class name .field-focus
}
inputView.show().focus(); //focus and show next input in table
}
<!doctype html>
<html lang="en">
<head>
<title>CLR: PACKING</title>
<meta charset = "UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet"
integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<?!= include("index-css"); ?>
</head>
<body>
<div class="conteiner">
<form novalidate>
<h6 class="title">PACKING</h6>
<div class="dws-input">
<div class="col-md-3"></div>
<div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tLogin" name= "username" placeholder= "Логин:" autofocus >
<label for="tLogin">Login:</label>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tTable" name= "text" placeholder= "Номер стола:" >
<label for="tTable">Table:</label>
</div>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" novalidate class="form-control" id="tOrder" name= "text" placeholder= "Заказ:" >
<label for="tOrder">Order:</label>
</div>
</div>
</form>
</div>
</body>
</html>
Thank you for help!
As Nitin mentions in the comment above, the Enter key is mainly used as a button press or submitting the form. Anyway, try this example for your solution.
const inputs = document.querySelector('.dws-input');
const formControl = document.querySelectorAll('.form-control');
formControl[0].focus();
function keyPressFunction(ev) {
if (ev.code !== 'Enter') return;
if (ev.target.value === '') return;
for (const i of formControl) {
if (i.value === '') {
i.nextElementSibling.focus();
break;
}
}
}
inputs.addEventListener('keydown', keyPressFunction);
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous" />
<div class="conteiner">
<form novalidate>
<h6 class="title">PACKING</h6>
<div class="dws-input">
<div class="col-md-3"></div>
<div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tLogin" name="username" placeholder="Логин:" autofocus />
<label for="tLogin">Login:</label>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" class="form-control" novalidate id="tTable" name="text" placeholder="Номер стола:" />
<label for="tTable">Table:</label>
</div>
</div>
<div class="form-floating mb-3 mt-3">
<input type="text" novalidate class="form-control" id="tOrder" name="text" placeholder="Заказ:" />
<label for="tOrder">Order:</label>
</div>
</div>
</form>
</div>
Please use this code.
const ids = $(":input").toArray().map(val => val.id);
$(":input").keypress(function keyPressFunction(e) {
const nextId = (ids.indexOf(document.activeElement.id) + 1) % ids.length;
if (e.which === 13 || e.keyCode === 13 ) {
document.getElementById(ids[nextId]).focus();
}
});

JavaScript and HTML doesn't show me form validation

as soon as I started doing a site. I did what I did before I got to js.
I have a form and I want to validate it all, I wrote the code for a validation but it does not display my validation, there is no error in js console. So.
Here's the code for form;
<body>
<div class ="container">
<div class="card mx-auto" style="width: 30rem;">
<div class="card-header">Register</div>
<div class="card-body">
<form name="form_register" onsubmit="return false" autocomplate="off">
<div class="form-group">
<label for="username">Username</label>
<input type="text" name="username" class="form-control" id="username" placeholder="Enter username">
<small id="user_error" class="form-text text-muted"></small>
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="email_error" class="form-text text-muted">We'll never share your email with anyone else.</small>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="password1" placeholder="Password">
<small id="pass_error" class="form-text text-muted"></small>
</div>
<div class="form-group">
<label for="exampleInputPassword2">Re-enter Password</label>
<input type="password" class="form-control" id="password2" placeholder="Re-enter Password">
<small id="pass1_error" class="form-text text-muted"></small>
</div>
<div class="form-group">
<label for="exampleFormgender">Gender</label>
<select class="form-control" id="gender">
<option>Male</option>
<option>Female</option>
</select>
<small id="gender_error" class="form-text text-muted"></small>
</div>
<div class="form-group">
<label for="exampleFormgrade">Grade</label>
<select class="form-control" id="grade">
<option>Admin</option>
<option>User</option>
</select>
<small id="grade_error" class="form-text text-muted"></small>
</div>
<br/>
<button type="submit" name="submit" id="submit" class="btn btn-primary"><i class="fa fa-user"> </i>Register</button>
<span>Login</span>
</form>
</div>
</div>
</div>
<br/>
</body>
and here is the js code.
$(document).ready(function(){
$("#form_register").on("submit",function(){
var status = false;
var name = $("#username");
var email = $("#email");
var pass1 = $("#password1");
var pass2 = $("#password2");
var genderx= $("#gender");
var type = $("#grade");
// var n_patt = new RegExp(/^[A-Za-z]+$/);
var e_patt = new RegExp(/^[a-z_-0-9_-]+(\.[a-z0-9_-]+)*#[a-z0-9_-]+(\.[a-z0-9_-]+)*(\.[a-z]{2,4})$/);
if (name.val() == "" || name.val().length < 2){
name.addClass("border-danger");
$("user_error").html("<span class='text-danger'>Please enter the name</span>");
status = false;
}else{
name.removeClass("border-danger");
$("user_error").html("");
status = true;
}
})
})
I can not see where the problem is, I do not know. Maybe it's not good the HTML code written or js. I really do not know, I tried .. I still wrote and rewritten .. and nothing.
Also, in the head, I put the location for js (main.js) and links for bootstrap, ajax, jquery.
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Register</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<script type="text/javascript"src="./js/main.js"></script>
</head>
In Jquery, when you use $("#form_register") it looks for the element on your HTML with the id "form_register" because you placed a #, it doesn't matter that your form has that name, it should also have an id with that name if you want to use like that.
<form id="form_register" onsubmit="return false" autocomplate="off">
Also your Regex has a mistake, you can test it in some webistes like regex101. I currently fixed the error on your Regex, but I don't know if it works as you expect it.
Here's the Regex:
^[a-z_0-9_-]+(\.[a-z0-9_-]+)*#[a-z0-9_-]+(\.[a-z0-9_-]+)*(\.[a-z]{2,4})$

Javascript doesn't work for input validation

I have seen many different ways to do it, and any of them works me.
I am using bootstrap.
The form goes directly to the 'action' (I want to validate first on 'onupdate')
SCRIPT:
[...]
<!-- Bootstrap core CSS -->
<link href="../css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="../css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="../style.css" rel="stylesheet" type="text/css/">
<script type="text/javascript">
function valForm()
{
alert("HALOOOOOOOOO");
var errors = 0;
var title = document.forms["tutorial_form"]["title"].value;
var description = document.forms["tutorial_form"]["description"].value;
var url = document.forms["tutorial_form"]["url"].value;
if (title == null || title == "")
{
document.getElementById("title_div").style.class = "form-group has-warning";
errors++;
}
if (description == null || description == "")
{
document.getElementById("description_div").style.class = "form-group has-warning";
errors++;
}
if (url == null || url == "")
{
document.getElementById("url_div").style.class = "form-group has-warning";
errors++;
}
if( errors > 0)
{
document.getElementById("error_container").innerHTML = "<div class="alert alert-danger" role="alert"><p><b>ERROR!</b>All the information must be fulfilled.</p></div>";
return false;
}
}
</script>
</head>
FORM:
<div class="container">
<form name="tutorial_form" enctype="multipart/form-data" action="insert_tutorial.php" onsubmit="return valForm()" method="post">
<div id="title_div" class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Title input">
</div>
<div id="description_div" class="form-group">
<label for="description">Description</label>
<textarea class="form-control" id="description" name="description" placeholder="Description" rows="5"></textarea>
</div>
<div id="url_div" class="form-group">
<label for="url">Video URL</label>
<input type="text" class="form-control" id="url" name="url" placeholder="Insert youtube url">
</div>
<div class="form-group">
<label for="file">Insert image file</label>
<input type="file" name="image" id="file">
<p class="help-block">Select the file. Take care that it's size is no longer that 16 MB.</p>
</div>
<input type="submit" value="Submit" name="submit" class="btn btn-success">
</form>
<hr>
</div>
Thank you in advance!!!
You have a syntax error in your last if statement, change the double quotes to single ones:
document.getElementById("error_container").innerHTML = "<div class='alert alert-danger' role='alert'><p><b>ERROR!</b>All the information must be fulfilled.</p></div>";
or you can escape them as well:
"<div class=\"alert alert-danger\" role=\"alert\"><p><b>ERROR!</b>All the information must be fulfilled.</p></div>";

Categories