/*
Requirements:
- Use ajax via the add_user function to submit the user entered data.
- You can assume the service will respond with 200 status.
- Display an error in red at the top of the form when the add user service responds with success property with a value of false.
Use the error property as the message.
- Display new users in the users list when the response returns a success property
- Highlight the email input when a user enters an invalid email address. Also, display the text "please enter a valid email address" in red.
NOTE: The service will not provide this validation functionality, and will accept invalid emails.
*/
$(document).ready(function () {
//create a space to display error messages that can be cleared of data when errors are no longer present
$('#form').prepend("<span class='errormsg'></span><br>");
$('#button').click(function () {
//ensure error indications from the previous submission are removed
$('input').addClass('validfield').removeClass('errorfield');
$('span.errormsg').empty();
$userInput = $('#username').val();
$emailInput = $('#email').val();
addUser($userInput, $emailInput, function (response) {
if (response.success === false) {
$('.errormsg').html(response.error);
} else if (validateEmail($emailInput) === false) {
$('#email').addClass('errorfield');
$('.errormsg').html("please enter a valid email address");
} else if (response.success === true) {
//$('.errormsg').empty();
$('#users').html(response["user"].username + " ... " + response["user"].email);
}
});
});
});
function validateEmail(email) {
var atpos = email.indexOf("@");
var dotpos = email.lastIndexOf(".");
if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
return false;
}
}
//example usage.
addUser('john',...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.