Skip to content

Instantly share code, notes, and snippets.

@msramalho
Created January 16, 2018 16:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save msramalho/039e96a45d956b2240b62deba6867dbb to your computer and use it in GitHub Desktop.
Save msramalho/039e96a45d956b2240b62deba6867dbb to your computer and use it in GitHub Desktop.
Solution for question 3 of the LTW Exam (2016-01-19) - javascript and Ajax
<form id="register" action="register.php" method="post">
<input name="username" type="text">
<input name="password" type="password">
<input type="submit" value="Register">
</form>
<script>
"use strict";
// (a) When the password input loses focus, it is verified if it contains at least 8 characters with at least one of them being a symbol other than a letter, a number or an underscore. If that's not the case, the input's border should become red.
let pass = document.querySelector('#register input[name="password"]');
pass.addEventListener("blur", event =>{
if(pass.value.length < 8 || pass.value.match(/[^\w]/) == null)
pass.style.borderColor = "red";
});
// (b) When the submit button is clicked, the value of the username input should be sent, inside a variable named username, in an Ajax POST request to the address verifyusername.php. If the response indicates that the username is not valid, the border of the input should become red and the form should not be submitted. Consider that the result, in JSON format, can be either {"valid": "true"} or {"valid": "false"}.
let username = document.querySelector('#register input[name="username"]');
let submit = document.querySelector('#register input[type="submit"]');
let form = document.querySelector("form#register");
submit.addEventListener("click", event => {
event.preventDefault();
let req = new XMLHttpRequest();
req.open("post", "verifyusername.php", true);
req.setRequestHeader("Content-type", "application/json");
req.onload = function(){
let res = JSON.parse(req.responseText);
if(res.valid == "true") form.submit();
else username.style.borderColor = "red";
}
req.send(JSON.stringify({username: username.value}));
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment