Internet-programming-UlSTU/Lab3/js/sendToServer.js
2023-11-17 16:55:32 +04:00

68 lines
1.7 KiB
JavaScript

import {createObject} from "./restApi";
const serverUrl = "http://localhost:8081";
let forma = document.querySelector(".form-container");
let handle = document.querySelector("input.handle");
let email = document.querySelector("input.email");
let password = document.querySelector("input.password");
export function checkUserInfo(){
let reg = /\w+@+\w+\.+\w/gi;
let flag = false;
if(!reg.test(email.value)){
email.style.background = "red";
email.focus();
flag = true;
}
else{
email.style.background = "white";
}
reg = /^\w*$/gi;
if(!reg.test(handle.value)){
handle.style.background = "red";
handle.focus();
flag = true;
}
else{
console.log(1);
handle.style.background = "white";
}
reg = /^\w*$/gi;
if(!reg.test(password.value)){
password.style.background = "red";
password.focus();
flag = true;
}
else{
password.style.background = "white";
}
return flag == false;
}
forma.addEventListener("submit", function(e){
console.log(1);
e.preventDefault();
if(checkUserInfo() == false){
return;
}
let user = createObject(handle.value, email.value, password.value);
postData("/users", user).then(res => console.log(res)).then(window.location.href = "/RegisterSuccessPage.html");
});
const postData = async (url, data) => {
const options = {
method: "POST",
body: JSON.stringify(data),
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
};
const response = await fetch(`${serverUrl}/users`, options);
if (!response.ok) {
throw response.statusText;
}
return response.json();
};