Phone Number Regex Validation error while showing/hiding Elements - javascript

I am working on a form where I am showing a div when a user submits the form and it checks if all the fields values are not blank. I have achieved that part and it is working fine.
Now the problem is when I am validating the phone number using regex, it is showing error but still displays the div and form is also submitted successfully. It should not get submit till the user enters a correct phone number, it gives an error and still, the form gets submitted. I know the error is there but I am not understanding where I am wrong. Please guide me.
function mySub() {
const user = document.getElementById('pmname').value.trim();
const uemail = document.getElementById('pmemail').value.trim();
const uphone = document.getElementById('pmphone').value.trim();
const uregx = /^[0-9]{10}$/;
const upmmb = uregx.test(uphone);
if (user == "" || uemail == "" || uphone == "" || upmmb == "") {
document.getElementById('agy').style.display = 'none';
alert("Enter Valid Mobile Number");
document.getElementById('pmphone').focus();
} else {
document.getElementById('agy').style.display = 'block';
}
}
#agy {
display: none;
}
<form method="post" action="#">
<div id="agy">
<div class="agent-details">
<div class="d-flex align-items-center">
<div class="agent-image">
<img class="rounded" src="#" alt="Jazz" width="70" height="70" />
</div>
<ul class="agent-information list-unstyled">
<li class="agent-name"><i class="houzez-icon icon-single-neutral mr-1"></i> Jazz</li>
<li class="agent-link">View Listings</li>
</ul>
</div>
</div>
</div>
<div class="form-group">
<input class="form-control" name="name" id="pmname" value="" type="text" placeholder="Name" />
</div>
<div class="form-group">
<input class="form-control" name="mobile" id="pmphone" value="" type="text" placeholder="Phone" />
</div>
<div class="form-group">
<input class="form-control" name="email" id="pmemail" value="" type="email" placeholder="Email" />
</div>
<div class="form-group form-group-textarea">
<textarea class="form-control hz-form-message" name="message" rows="4" placeholder="Message">Hello, I am interested in ...</textarea>
</div>
<div class="form-group">
<label class="control control--checkbox m-0 hz-terms-of-use">
<input type="checkbox" id="ppa" name="privacy_policy" checked="" />By submitting this form I agree to <a target="_blank" href="https://propertymakkerz.com/pm/property/sai-ashishkaranjadepanvel/">Terms of Use</a>
<span class="control__indicator"></span>
</label>
</div>
<div class="form_messages"></div>
<button type="button" class="houzez_agent_property_form btn btn-secondary btn-full-width" onclick="mySub()"><span class="btn-loader houzez-loader-js"></span> Send Message</button>
</form>

Related

Javascript, validation of password with bootstrap

i'm trying to learn Javascript and some basic HTML with bootstrap v5.
I created a Sign-in form and now i'm try to do some validation for the required field.
I follow the Bootstrap documentations and i managed to get validation for all my input field except for the password, i want to verify if the password are the same or if they are empty field...but i'm stuck.. not familiar with javascript.
my attempt in javascript:
let forms = document.querySelectorAll(".needs-validations");
let pass1 = document.getElementById("password1");
let pass2 = document.getElementById("password2");
Array.prototype.slice.call(forms).forEach( function (form){
form.addEventListener("submit",function (ev) {
// test password check....
if (pass1.value !== pass2.value || pass1.value === "" || pass2.value === "" ){
pass1.className = 'form-control is-invalid'
pass2.className = 'form-control is-invalid'
}
if (!form.checkValidity()){
ev.preventDefault()
ev.stopPropagation()
}
form.classList.add("was-validated")
})
})
but here the result:
As you can see password is always valid and i don't understand why.
my html:
<body class="body">
<div class="center">
<h4 class="title">Sign Up New User</h4>
<form name="signin-form" method="post" class="needs-validations" novalidate id="forms">
<div class="container">
<div class="row mt-3">
<div class="col">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name" required>
<div class="invalid-feedback">
Name can't be empty
</div>
</div>
<div class="col">
<label for="surname" class="form-label">Surname</label>
<input type="text" class="form-control" id="surname" placeholder="Surname" required>
<div class="invalid-feedback">
Surname can't be empty
</div>
</div>
</div>
<div class="row mt-3">
<div class="col">
<label for="email" class="form-label">Email</label>
<input type="email" class="form-control" id="email" placeholder="Email" required>
<div class="invalid-feedback">
invalid email
</div>
</div>
<div class="col-4 text-end">
<label for="email" class="form-label">Role</label>
<select class="form-select" id="validationCustom04" required>
<option selected disabled value="">Choose...</option>
<option>Captain</option>
<option>First Officer</option>
</select>
<div class="invalid-feedback">
Please select role
</div>
</div>
</div>
<div class="row mt-3 ">
<div class="col">
<label for="password1" class="form-label ">Password</label>
<input type="password" class="form-control" id="password1" placeholder="Password">
</div>
<div class="col">
<label for="password2" class="form-label ">Confirm Password</label>
<input type="password" class="form-control" id="password2" placeholder="Password">
<div class="invalid-feedback">
Password not match
</div>
</div>
</div>
<div class="row-cols-2 mt-3">
<button class="btn btn-primary" type="submit">Submit form</button>
</div>
</div>
</form>
</div>
<script src="/validation.js"></script>
<script src="/js/bootstrap.bundle.min.js" ></script>
</body>
What I don't understand is, that your password fields seem to be having a valid class in your posted screenshot. But I can't find it anywhere in your code (neither HTML nor JS).
I'd do it like this:
(Note: I didn't test this code, but it should work. If it works and you want to learn from it, I recommend to read through it step by step and apply it to your logic instead of just copy pasta.)
let form = document.querySelector("form.needs-validations");
// or, to be more specific:
// let form = document.querySelector("form[name='signing-form']")
form.addEventListener("submit",function (ev) {
let pass1 = document.getElementById("password1");
let pass2 = document.getElementById("password2");
// test password check....
if (pass1.value !== pass2.value || pass1.value === "" || pass2.value === "" ){
pass1.classList.add('is-invalid');
pass2.classList.add('is-invalid');
}
if (!form.checkValidity()){
ev.preventDefault();
ev.stopPropagation();
}
form.classList.add("was-validated");
})
Note: the functionality to validate the content of your password-fields will only be triggered once you hit the submit button.

Form continues to submit despite custom validation logic

I have developed some logic to display relevant errors when the form is submitted, but it continues to allow me to submit the form without displaying the errors. I used a flag to determine whether the form should be submitted, but it seems to be ignored, it's just not working.
if (this.formId == "challengeQuestionAuth") {
return new Promise(function (resolve, reject) {
debugOut("Question: " + _this.payload.question, "alert");
let div = document.createElement('div');
div.innerHTML = `
<div id="contentWrapper" style="display: block;">
<div class="page">
<div class="page-body">
<div>
<div class="page-title">Online Banking Security Challenge</div>
<div class="main-section">
<div class="page-instructions">
This action requires you to answer a security question before it can be completed.
</div>
<form class="form" method="post" name="security_challenge" id="security_challenge">
<input type="hidden" />
<div class="validation-summary-valid alert alert-error" data-valmsg-summary="true">
<span>
Please correct the highlighted field(s) below.
</span>
<ul>
<li style="display: none;"></li>
</ul>
</div>
<div class="content-panel">
<fieldset>
<input name="Text" id="Text" type="hidden" value="What is your best friend's middle name?" />
<input name="" id="" type="hidden" value="" />
<div class="challenge-question">
<label for="challengeResponse">
${_this.payload.question}
</label>
</div>
<div class="challenge-answer">
<input aria-required="true" name="challengeResponse" class="control" id="challengeResponse" autofocus="autoFocus" type="password" autocomplete="off">
<span class="error"><p id="answer_error"></p></span>
<input class="checkbox" id="ShowAnswer" type="checkbox">
<label class="label" for="ShowAnswer">Show answer</label>
<span class="field-validation-valid" data-valmsg-replace="true" data-valmsg-for="Answer"></span>
</div>
<div class="action-group-bottom">
<a id="cancelButton" class="cancel-button contextual-link" href="">Cancel</a>
<input name="Action:SecurityQuestion" id="continueButton" class="primary-action orange-button" type="submit" data-clear-alerts="true" value="Submit" />
</div>
</fieldset>
</div>
</form>
</div>
<div aria-required="true" name="challengeQuestion" type="text" id="challengeQuestion">${_this.payload.question}</div><br />
<label class="control-label" for="challengeResponse">Response:</label>
</div>
</div>
</div>
</div>`;
uiContainer.appendChild(div);
document.getElementById("security_challenge").onsubmit = function() {
const answer = document.forms["security_challenge"]["challengeResponse"].value;
const submit = true;
if (answer == null || answer == "") {
answerError = "Please provide an answer.";
document.getElementById("answer_error").innerHTML = answerError;
submit = false;
}
return submit;
}
Here is a minimally reproducible example:
https://codepen.io/ldco2017/pen/dyMMpjb?editors=0010
I was able to disallow the form to be submitted with what I have below. Adding strict comparison operator to if statement and change const submit to let submit because you are reassigning it.
let submit = true;
if (answer === null || answer === "") {
answerError = "Please provide an answer.";
document.getElementById("answer_error").innerHTML = answerError;
submit = false;
}

Javascript doesnt seem to be attachet to my jsp

When i load login.jsp it doesn't alert if i dont input password or username
tried checking wether i correctly attached the file but it still doesnt work for me, what could be the reason?jsp just reacts the way it would react if i wouldn't use js at all
LoginPage.js
function check()
{
var username = document.form.username.value;
var password = document.form.password.value;
if (username==null || username=="")
{
alert("Username can't be blank");
return false;
}
else if(password==null||password=="")
{
alert("Password must be inserted ");
return false;
}
}
my jsp:
<body>
<div class="card-body">
<form method="get" action="LoginServlet" onsubmit="return check()">
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-user"></i></span>
</div>
<input id="username" type="text" class="form-control" placeholder="username" name="username">
</div>
<div class="input-group form-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="fas fa-key"></i></span>
</div>
<input id="password" type="password" class="form-control" placeholder="password" name="password">
</div>
<div class="form-group">
<input id="login-button" type="submit" value="Login" class="btn float-right login_btn" >
</div>
</form>
</div>
<div class="card-footer">
<div class="d-flex justify-content-center links">
Don't have an account?Sign Up
</div>
</div>
</div>
</div>
</div>
<script src="LoginPage.js"></script>
</body>
</html>
any suggestions ?
firstly check the HTML syntax of your jsp, it seems that the html is broken because of the last three </div> because of the missing opening tags.
Then, you don't have by default a document.form property so you could get your username and password in the following way:
// or you can use document.getElementById('username')
const username = document.querySelector('#username').value;
const password = document.querySelector('#password').value;
here details about the querySelector function

How to get values from input boxes and save to database with button click angular

I'm still learning to programme on AngularJS.
I want to get values from the input box and then click on the button I want to save them in the database.
My database table is called "user". I have columns like id, username, password, name.
I have two checkbox.When I click on first checkbox(Edit) it displaying "div myVar",when i click on second checkbox(Add new user) it displaying "div myVar1".
I want to activate this button "Add" to add input box values to database MySQL. Please help me.
I have this html code:
<label><input type="checkbox" ng-model="myVar">Edit</label>
<label><input type="checkbox" ng-model="myVar1">Add new user</label>
<div ng-show="myVar">
<div class="form">
<form ng-submit="saveItem(userForm.$valid)" name="userForm">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="database_address">User</label>
<input type="text" class="form-control" required ng-model="activeItem.username" placeholder="Потребителско Име..." />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="text" class="form-control" required id="password" ng-model="activeItem.password" />
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="username">Operator</label>
<input type="text" class="form-control" required id="username" ng-model="activeItem.name" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Save</button>
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form><form ng-submit="createUser(userForm.$valid)" name="userForm1">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="database_address">User</label>
<input type="text" class="form-control1" ng-model="usernamee" placeholder="Потребителско Име..." />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="text" class="form-control1" ng-model="passwordd"required id="password" />
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label for="username">Operator</label>
<input type="text" class="form-control1" ng-model="namee" required id="username" />
</div>
</div>
</div>
<button class="btn btn-primary" ng-click="createUser();" type="submit">Add user</button>
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
And Angular code:
$scope.createUser=function()
{
//console.log($scope.activeItem);
//delete $scope.activeItem.hash_method
var objectToSave = {
username: $scope.usernamee,
password: $scope.passwordd,
name: $scope.namee,
id: $scope.id
};
{
defaultAdapter.query('INSERT INTO users(username,password,name,id) VALUES(username = :usernamee, password = :passwordd,name = :namee WHERE id =:id)',
{ replacements: objectToSave, type: Sequelize.QueryTypes.UPDATE }
).then(projects => {
console.log(projects);
$scope.editMode = false;
$scope.activeItem = false;
$scope.refresh();
});
}
}

How to send localstorage with form

I have html form and localstorage
I need send data from localstorage and form on email
Now I am sending two letter :(
When user submit form I get two letter. First letter from form and second letter from localstorage
So, I want get one letter with localstorage and form
My form:
<form action="/send.php" id="form-cart-send" onsubmit="return sendCartdata();" method="post" enctype="multipart/form-data" required>
<div class="form_fields" data-count="3">
<div class="form_field" data-type="name" data-is-required="true">
<label class="field_title">Имя<i>*</i></label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="name" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="phone" data-is-required="1">
<label class="field_title">Телефон<i>*</i></label>
<div class="form_field_text">
<input type="tel" class="form_field_text_input form_phone" id="phone" name="phone" data-check="phone" autocomplete="off" required>
</div>
</div>
<div class="form_field" data-type="email" data-is-required="0">
<label class="field_title">Ваш e-mail</label>
<div class="form_field_text">
<input type="text" class="form_field_text_input" name="email" data-check="email" autocomplete="off" required>
</div>
</div>
</div>
<div class="form_fields_advanced"></div>
<div class="form_submit">
<a class="component-button form_field_submit filled squared" id="checkout" data-modal-id="cart_done">
<div class="btn-content">
<div class="form_submit_text">Заказать</div>
</div>
</a>
</div>
</form>
Script for localstorage:
<script>
function sendCartdata() {
var phone = document.getElementById("phone").value;
if (phone === '') {
alert("Заполните, пожалуйста, обязательные поля.");
return false;
} else {
setTimeout(function() {
var value = localStorage.getItem('cart');
jQuery.post("/cart-send.php", {
cart: value
}, function(data) {
}).fail(function() {
alert("Damn, something broke");
});
}, 100);
return false;
}
}
</script>

Categories

Resources