Javascript Validation - javascript

I am wanting to make validation to my Email form. Unfortunately I cannot get this piece of code to work. When I am clicking submit without entering any data in to the form it will send.
I am wanting it not to send without the right Characters in the Email
I have attached a screenshot below of my code

You need to change your regex as:
var email_regex = /^[\w%_\-.\d]+#[\w.\-]+.[A-Za-z]{2,6}$/; // reg ex email check
if(emailAddress == "")
{
// error if empty
}
else
{
if(!email_regex.test(emailAddress))
{
// invalid error
}
else
{
// success
}
}

Related

Email Validation using setCustomValidity

I got the following code for
// Validating Email
function validateEmail() {
var mail = document.getElementById("email").value;
var mailformat = /^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{3})+$/;
var endEmail = "#gmail"
if(mail.match(mailformat) && (mail.charAt(x.length-1) == endEmail) ) {
mail.value += ".com"
alert(mail)
return true;
} else if (email.validity.valueMissing) {
console.log("Email is missing")
email.setCustomValidity("Please fill in the email.");
}
}
I have a problem with checking the email. The logic I am trying to implement is to check whether the email contains “gmail” after “#” and to validate the email ends in “.com” (This check is only mandatory if the email field has “gmail” after “#”.). In the case of gmail being in the email after “#” and the ending being something other than “.com”, I wanna fix this for the user and let the submission go through after the fix.

Alert popping up multiple times and submit button only working after second click

I am working on my CS50 Final Project. I am designing a web app:
I am using flask.
This happens in the login/register page.
I am trying to check if the username is already taken( through jsonify) and if the password and the password confirmation are equal using JS.
So basically the problem is:
After loading tha page and filling out the register form nothing happens on the first click on the submit button. On the second click everything works just as it is supposed to: the functions run fine and check for matching passwords and if the username is available and alert if necessary. If I then close the alert window and click the submit button again I get two alerts from the usercheck function.
If do the same thing again 3 alerts then 4 and so on....For some reason the function gets called again and again but I can't figure out where....
Here's the HTML:
<form id='register' action='/register' method="POST" onsubmit="return !!(passwordcheck() & usercheck());" ></form>
Here's the two JS function in a script tag in the same page:
function passwordcheck(){
const password = document.getElementById('password').value;
const passwordc = document.getElementById('passwordc').value;
if (password != passwordc){
alert('Passwords do not match')
return false;
}
}
function usercheck(){
$('document').ready(function(){
$('form').on('submit',function(e){
e.preventDefault();
var username = document.querySelector('#username').value;
$.get('/check?username=' + username, function(r){
if(r == false){
alert('User taken');
$('#username').focus();
}
else{
(document).getElementById('register').submit();
}
} )
})
})
}
And here's the Python code from the application.py file that querys the database for the username:
#app.route("/check", methods=["GET"])
def check():
print(Fore.BLUE + "check function, line 99")
"""Return true if username available, else false, in JSON format"""
username = (request.args.get('username'),)
if username:
c.execute("SELECT username FROM users WHERE username =?", username)
old_user = c.fetchall()
if len(old_user) > 0:
return jsonify(False)
else:
return jsonify(True)
You have defined two handlers for the form submit event:
- the first in the html (onsubmit="return !!(passwordcheck() & usercheck());") is the userCheck function that does not actually make a request
- the second inside the userCheck function ($('form').on('submit',function(e){) that does make a request
So the first time you submit the userCheck function is called, it does not make a request but add a submit event handler to the form. That is why the request is made only after submitting the form a second time.
You should be better off with something like this:
function passwordcheck() {
const password = document.getElementById('password').value;
const passwordc = document.getElementById('passwordc').value;
if (password != passwordc) {
alert('Passwords do not match')
return false;
}
}
function usercheck(handleSuccess, handleError) {
var username = document.querySelector('#username').value;
$.get('/check?username=' + username, function(r) {
if (r == false) {
handleError();
} else {
handleSuccess();
}
})
}
function submit() {
(document).getElementById('register').submit();
}
function handleUserError () {
alert('User taken');
$('#username').focus();
}
$('document').ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
if (!passwordcheck()) {
return;
}
usercheck(submit, handleUserError);
})
})
and without the onsubmit attribute on your form element.

Dynamically change div content in a form submission

I have created one login page with some error message.But I am able to display only single error message.My Requirement is very simple.
I have 2 fields email and password when I click go button if there is no email it should display enter email.If I have entered invalid email it should display invalid email.
Similary for password two validation enter passwordand enter valid password.
For this I need to add error messages dynamically.Can anybody help me ?please.
https://jsfiddle.net/jnzk9gv4/
The fastest way here is to simply change the message when you detect a problem.
here you have: https://jsfiddle.net/jnzk9gv4/7/
var error = "";
if (!emailReg.test(userEmail)) {
error = "Invalid email";
} else if (userEmail=="") {
error = "Enter email";
} else if (!passReg.test(userPassword)) {
error = "Invalid password";
} else if (userPassword=="") {
error = "Enter password";
}
if (error != "") {
$("#errorMessage").text(error);
$(".invalidData").show();
} else {
$(".invalidData").hide();
}

How to check if USERNAME already exists in PHP/MYSQL?

I'm currently configuring my "User Registration" form in PHP.
Trying to create a simple function to check if the username already exists in the database
After doing my research, I have found that there are several ways this can be done.
(a) the best way is probably to use a PHP/AJAX combination, to check right away if the username already exists (in other words, the check is done BEFORE the user clicks the "Submit" button;
(b) the other way is to do a simple SQL-query, which will return an error message, if that particular username already exists in the database. (The only drawback with this method is that : the check is done only AFTER the user clicks the "Submit" button.
I would have preferred Option A, of course. But, I was unsuccessful in my attempts to create a working AJAX/jQuery script.
So, I went with Option B instead.
And, I got it working.
Here is the simply query I used :
if(isset($_POST['submit1'])||isset($_POST['submit1'])) {
$login = $_POST['login'];
$query_login = "SELECT login FROM registration WHERE login='$login';";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "Sorry, that Username is already taken. Please choose another.";
return false; }
else { //proceed with registration
It worked fine. The error was displayed.
The only problem is : the registration form itself disappeared.
I would have liked to display the error on the same page as the registration form, without having to RESET or somehow GO BACK.
I know that the reason for this is something very minor (and kinda stupid on my part :D :D)
Probably something to do with that "return false" thingy at the end of the query.
But, I am not sure.
(a) How can I get the error message displayed on the form-page itself?
(b) Or, better yet, is there a JavaScript Function I can use for this, so that I can simply call the function in the "Submit" button................like so : onSubmit = return function() ??
Thanks
UPDATE: Here is my form code.
form action="myform.php" method="post">
<br>
Choose a username : <input type="text" name="login" value="<?=$login?>"
required>
UPDATE
I was able to find the following jQuery code :
$(document).ready(function() {
//the min chars for username
var min_chars = 3;
//result texts
var characters_error = 'Minimum amount of chars is 3';
var checking_html = 'Checking...';
//when button is clicked
$('#check_username_availability').click(function(){
//run the character number check
if($('#username').val().length < min_chars){
//if it's bellow the minimum show characters_error text '
$('#username_availability_result').html(characters_error);
}else{
//else show the cheking_text and run the function to check
$('#username_availability_result').html(checking_html);
check_availability();
}
});
});
//function to check username availability
function check_availability(){
//get the username
var username = $('#username').val();
//use ajax to run the check
$.post("check_username.php", { username: username },
function(result){
//if the result is 1
if(result == 1){
//show that the username is available
$('#username_availability_result').html(username + ' is
Available');
}else{
//show that the username is NOT available
$('#username_availability_result').html(username + ' is not
Available');
}
});
}
I assume that, for my particular example :
(a) the jQuery file cannot be inserted into the actual PHP file (my php file is named : registration.php, which includes both the html and php);
(b) this particular jQuery file includes a "button", which needs to be clicked to check if the username already exists. This is not a bad idea; but, I would rather that this was done automatically, without the need to click on a button (let's face it : there are some users out there who are indeed too clueless to perform this simple check manually). My aim is free the user as much as possible from the need to do such trivial tasks :D
Anyway, my point is : so as to eliminate the need for a button, I would like to include an auto-function which checks once the user types in the username.
According to Google, the following function is what I need :
Replace $(‘#check_username_availability’).click(function(){ … with $(‘#username’).keyup(function(){ …
(c) Isn't there any way to actually insert that JQUERY into "registration.php" ?? Or, should it be a separate file entirely?
The better way would be you bind the ".blur" event on which you may check if the username is valid via ajax. Don't forget to check the username after form submission at before form submission.
Below your input box create a
<span class= "error">Username is already present. </span>
<span class= "success">Username can be assigned. </span>
and just display the message accordingly.
You may use the script as
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {"username",$("input.username").val()},
success : function (data)
{
if(data == "success")
{$(".success").show();$(".error").hide();}
else
{$(".error").show();$(".success").hide();}
},
});
You php code would be something like this :
$query = "SELECT username FROM tab_users WHERE username = '".$_POST['username']."'";
$result_login = mysqli_query($conn,$query_login);
$anything_found = mysqli_num_rows($result_login);
//check if the username already exists
if($anything_found>0)
{
echo "fail";
return false;
}
else
{
echo "success";
return false;
}
You can disable the submit button and add a span message near the input field.
Check this code:
function checkUsername()
{
var username = document.getElementById('username');
var message = document.getElementById('confirmUsername');
/*This is just to see how it works, remove this lines*/
message.innerHTML = username.value;
document.getElementById("send").disabled = true;
/*********************************************/
$.ajax({
url : "check_username.php",// your username checker url
type : "POST",
data : {username: username},
success: function (response) {
if (response==0)
{
message.innerHTML = "Valid Username";
document.getElementById("send").disabled = false;
}
if (response==1)
{
message.innerHTML = "Already Used";
document.getElementById("send").disabled = true;
}
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<label for="uername">Username:</label>
<input type="text" class="form-control" name="username" id="username" onkeyup="checkUsername(); return false;" required/>
<span id="confirmUsername" class="confirmUsername"></span>
<button type="submit" id="send" name="action" value="Send">Send</button>
put this
include([your validating php file]);
and in your form action link to your login form file.
note : your login file have to be php file.

Form submit add domain to username field if missing

I have a login form that includes a username and password field.
Users will be able to login using:
Domain\username
And
Username#domain.org.uk
However many users attempt to login using just 'username'
I want to help users by adding domain\ or #domain.org.uk to there username when they enter just 'username', when they click the login button I want to add the domain part of the username.
How can I do this in pure JavaScript?
function insertDomain (){
var txtBox = document.getElementById('Your_Textbox');
if(txtBox.value.indexOf("#") == -1)
{
txtBox.value += "#domain.org.uk";
}
}
On Submit: http://alexking.org/blog/2003/10/01/javascript-onsubmit-handler
Something along the lines of
var username = document.getElementById('username')
if(username.indexOf('#') < 0){
username = usename + '#domain.org.uk';
}

Categories