JSFiddle - React, Tailwind, and code Playground

by brianjsullivan

HTML

<h2>Add a User:</h2>

<form id="form">
    <input type="text" name="username" id="username" placeholder="name">
    <input type="email" name="email" id="email" placeholder="email">
    <input type="button" name="button" id="button" value="add user">
</form>

<h2>Users:</h2>

<ul id="users"></ul>

CSS

body {
    font-family: Helvetica, Sans, Arial;
}
p, ul {
    padding: 10px;
}
ul {
    margin: 5px;
    border: 2px dashed #999;
}
.errormsg {
    color: red;
}
.validfield {
    box-shadow:none;
}
.errorfield {
    box-shadow: 0px 0px 10px #FF0000;
}

JavaScript

/*
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',...