How to solve blur and submit event simultaneous in angular - javascript

I have text box in my page, which i can enter 9 digit number. Onblur I am validating like the entered number is valid or not using API call, If service returns failure it will clear the text box with red border and form will be invalid. The event conflict happening between OnBlur and Submit. Submit service will call only the form is valid otherwise it will show toaster like enter mandatory filed.
If the text field focused and directly if I click on submit button, both event calling simultaneously and it is clearing the number field OnBlur as well as the service is calling.
Please can you help me to resolve this conflicts.
file.html
<form class="contact-form" #create="ngForm">
<div class="controls">
<input NumberOnly="true" type="text" id="num" [ngClass]="{'red-border-class': ((showErrorFlag == true && numberField.errors) || (showErrorFlag == true && numberField.errors && (numberField.dirty || numberField.touched)))}"
[disabled]="disableRotaDetailFields" [(ngModel)]="number"
class="floatLabel" name="ownership" required #numberField="ngModel" (blur)="validatenumber(number)" [maxLength]="einLength">
<label for="ein">number<sup>*</sup></label>
</div>
<button (click)="SaveData(create)">Save</button>
</form>
file.ts
public validatenumber(number) {
let reqObj = {
"ownership": number
}
this.calloutService.validateOwnerEin(reqObj)
.pipe(takeUntil(this.unsubscribe))
.subscribe((data) => {
}, (err) => {
if (err.status == 404) {
this.number = "";
}
this.toastr.error(err.overriddenMessage);
})
}
SaveData(){
if (!formFlag.valid ) {
this.showErrorFlag = true;
this.toastr.error('Please fill all the mandatory fields');
}else {
this.calloutService.createData(this.data)
.pipe(takeUntil(this.unsubscribe))
.subscribe(data => {
this.showSpinnerFlag = false;
let response = data;
if (data) {
this.toastr.success("Rota created successfully.");
} else {
this.toastr.error("Could not save.");
}
}, err => {
this.showSpinnerFlag = false;
this.toastr.error(err.overriddenMessage);
})
}
}

Related

Avoid user click submit button more than once?

I'm working on a asp.net MVC project. On one page, it has many controls and features. When user clicks 'submit' button, it will do many validations in the controller for the input. If something is not right, it will show the error on the page. Otherwise, will save the data in the database with a Guid, and go to the next page.
The problem is: the validation takes some time, user may accidentally click the submit button more than once which results in saving data to the database with the same Guid, which throws an error since Guid has to be unique for each data.
Is there a way to prevent user clicking more than once? We can not simply disable the button after click. If the validation has issue, then user can not submit again since the button is disabled.
You can disable the submit button until all the validation has been completed. Track a variable for each conditional that returns true when the validation for that section of the form is complete and then check each of these variables at the end to make sure each one is true. If they are all true set the submit.disabled to false.
NOTE: You can do this with each input as well, disabling each input until the previous input has been properly validated.
Below is a very rudimentary example of this logic.
const submit = document.getElementById('submit')
const fname = document.getElementById('fname')
const lname = document.getElementById('lname')
const email = document.getElementById('email')
const inputs = document.querySelectorAll('.input')
function emailIsValid(email) {
return /^[^\s#]+#[^\s#]+\.[^\s#]+$/.test(email)
}
function nameIsValid(name) {
return name.match(/^[A-Za-z]+$/)
}
function validate(fname, lname, email, submit) {
// the validation variables to check at end to set submit.disabled to false
let fnameCheck = false,
lnameCheck = false,
emailCheck = false;
// check first name field
if (fname.value !== '' && fname.value.length > 1 && nameIsValid(fname.value)) {
fname.style.background = 'lightgreen'
fname.previousSibling.previousSibling.style.background = 'green'
fnameCheck = true
} else {
// JIC they delete reset to false
fnameCheck = false
fname.style.background = 'pink'
}
if (lname.value !== '' && lname.value.length > 2 && nameIsValid(fname.value)) {
lnameCheck = true
lname.style.background = 'lightgreen'
} else {
lnameCheck = false
lname.style.background = 'pink'
}
if (emailIsValid(email.value)) {
emailCheck = true
email.style.background = 'lightgreen'
} else {
emailCheck = false
email.style.background = 'pink'
}
// log for visual inspection of check-variable values
console.log(lnameCheck, fnameCheck, emailCheck)
// make sure all check-variables are set to true
if (fnameCheck === true && lnameCheck === true && emailCheck === true) {
submit.disabled = false
}
}
// event listener for each input on input field run the validate function
// and pass in our inputs and submit button for manipulation.
inputs.forEach(input =>
input.addEventListener('input', () => validate(fname, lname, email, submit))
)
<form action="#">
<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname" class="input"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname" class="input"><br>
<label for="email">email:</label><br>
<input type="text" id="email" name="email" class="input"><br>
<input type="submit" id="submit" value="Submit" disabled>
</form>

Cannot read property 'input' of null at HTMLDocument.<anonymous> Javascript/HTML 2 part login error

I am trying to create a 2 part login, 1st part where you enter the username, click login, and the login takes you to a page where you enter your password. I have a js function where I check if the username field is null, because I want to require the user to enter something in the text field before clicking the button redirects them to the second part of the login. However, I am getting an error: Uncaught ReferenceError: loginCheck is not defined at HTMLInputElement.onclick
here is my code
var formhtml = '<div class="container"><label for="userNameBox"><b>Username </b></label><input type="text" id="userNameBox" placeholder="Enter Username" required ="required"><br></br> <input type="button" id ="loginButton" value="Login"onclick="javascript:loginCheck()"/></div>'
function loginCheck(){
var x = null;
if(document.getElementById("userNameBox").value !=null){
document.getElementById("loginButton").onclick = function () {
location.href = "myLogin.Part2";
}
}
else{
alert("username required");
location.reload();
}
}
$('.login').click(function(e)
{
e.preventDefault();
if ($('#loginbox').html() == '')
$('#loginbox').html(formhtml);
$('#loginbox').show();
return false;
});
You seem to be mixing a lot of Vanilla JavaScript and jQuery. Although that's not wrong, it might help you with development by choosing one or the other.
Like #Teemu said, the value of an input is never null. If it is empty than the value will be represented as an empty string "".
The loginCheck function will add an event listener to the loginButton element. But that element already has an onclick attribute which calls the loginCheck function. This will not run as you would like it to. Instead of both add an event listener with either addEventListener (Vanilla JavaScript) or with the on method (jQuery)
I've tried to convert your code so that it uses jQuery. Check it out and let me know if your problem has been resolved.
const $document = $(document);
const $login = $("#login");
const $loginBox = $("#loginbox");
const $formElement = $(`
<div class="container">
<label for="userNameBox"><b>Username </b></label>
<input type="text" id="userNameBox" placeholder="Enter Username" required="required"><br>
<input type="button" id="loginButton" value="Login"/>
</div>
`);
$document.on("click", "#loginButton", function() {
const $userNameBox = $("#userNameBox");
if ($userNameBox.val() !== "") {
location.href = "myLogin.Part2";
} else {
alert("username required");
location.reload();
}
});
$login.on("click", function (event) {
if ($loginBox.children().length === 0) {
$loginBox.append($formElement);
}
$("#loginbox").show();
event.preventDefault();
return false;
});

Angular (JavaScript) Confirm password validation message?

so i have a password and confirm password and I obviously need to match and show a message if not match.
my requirements:
the message should only show after the confirm password (second input)input.
my setup now is, when user blur out confirm password(second input) the function runs and throw err message if no match and also is dynamically hidden when user type the correct password (used onkeyup) that matches password input (first input)
problem:
if the user go back and change the first input no message is shown. if I use the same onblur function on password (first input), then the message shows before I input anything in the second field (confirm password). how do i fix this?
$onInit = () => {
let self = this;
this.siRole.getRoles().then((roleList) => {
self.roleList = roleList.filter((r) => {return !r.hidden});
}, (err) => {
self.siAlertDialog.error(err.message);
})
this.hide = true;
}
passwordWatchOnblur = ()=>{
this.hide = this.newUser.password == this.newUser.confirmPassword ? true :false
}
passwordWatchOnkeyup = ()=>{
if(this.newUser.password == this.newUser.confirmPassword){
this.hide=true;
}
}
<div layout layout-xs='column'>
<md-input-container flex class="md-accent">
<label translate="LABELS.PASSWORD"></label>
<input ng-model='$ctrl.newUser.password' type='password' required/>
</md-input-container>
<md-input-container flex class="md-accent">
<label translate="LABELS.CONFPASS"></label>
<input id="confirm" ng-model='$ctrl.newUser.confirmPassword' type='password' ng-blur="$ctrl.passwordWatchOnblur()" ng-keyup="$ctrl.passwordWatchOnkeyup()" required/>
<span ng-hide="$ctrl.hide" class='label-error'>{{'SI-MESSAGES.PASS-NO-MATCH'|translate}}</span>
</md-input-container>
</div>
Possible solution:
Use the same onkeyup function on password (first input) and modify passwordWatchOnkeyup like tihs:
passwordWatchOnkeyup = () => {
this.hide = typeof this.newUser.confirmPassword === 'undefined' || this.newUser.confirmPassword === null || this.newUser.password == this.newUser.confirmPassword;
}
Why: If there is no confirmPassword or they both are equal, then hide message.
UPDATE (added alternative for passwordWatchOnblur function)
... or you can use this (passwordWatchOnblur) function on the onblur on password (first input)
passwordWatchOnblur = () => {
this.hide = typeof this.newUser.confirmPassword === 'undefined' || this.newUser.confirmPassword === null || this.newUser.password == this.newUser.confirmPassword;
}
P.S.: The content of the functions are the same. What changes is the time where they are called. With the passwordWatchOnblur being called on the onblur the message will not be shown until the user has left the input, and not while he/she is typing the password.

How to prevent Foxycart Action on submit with empty field?

Hollo All,
I am creating a form that exports data on submit to an ecommerce solution called Foxycart. I would like the form to only proceed onto foxycart when the date field is entered however it currently only displays the alert message then proceeds to the action on the form. Does anyone have advice on how to prevent the action on submit? please see code below:
<script>
function validateForm() {
var x = document.forms["delivery-date-info"]["Delivery_Date_is"].value;
if (x == null || x == "") {
alert("Date must be filled out");
return false;
}
}
</script>
<form name="delivery-date-info" action="https://austin-roman.foxycart.com/cart" method="post" accept-charset="utf-8" onsubmit="return validateForm()">
<div class="add-to-bag">
<label for="datepicker-example3"></label>
<input id="datepicker-example3" type="text" name="Delivery_Date_is">
<input type="submit" id="datepicker-example3" type="text" class="button-add">
</div>
</form>
Assuming you're using FoxyCart's default "sidecart" approach (as of v2.0), you'll need to use FoxyCart's own event system, described here. For your specific example, it might look like this:
var FC = FC || {};
FC.onLoad = function () {
FC.client.on('cart-submit', function(params, next) {
if (validateForm()) {
next();
}
});
};
function validateForm() {
var x = document.forms["delivery-date-info"]["Delivery_Date_is"].value;
if (x == null || x == "") {
alert("Date must be filled out");
return false;
} else {
return true;
}
}
Here's an alternate approach that'd be a bit more flexible, would allow more than one product form per page, and also shows a little more what's going on:
var FC = FC || {};
FC.onLoad = function () {
FC.client.on('cart-submit', function(params, next) {
$element = $(params.element);
if (
$element.attr('name') == 'delivery-date-info'
&& $element.find('[name="Delivery_Date_is"]').length > 0
&& !$element.find('[name="Delivery_Date_is"]').val()
) {
alert('Date must be filled out');
} else {
next();
}
});
};

tinyMCE jQuery form validation

I'm trying to use tinymce's getContent() to make a custom validation rule, how can I do this with jquery validation? I need to apply the rule to a textarea formatted with tinymce.
Validation: http://bassistance.de/jquery-plugins/jquery-plugin-validation/
$("#element").click( function(e) {
console.log(tinyMCE.activeEditor.getContent());
$("#someForm").validate({
rules: {
title: {
required: true
}
}
});
});
I'm thinking of just using a little bit of javascript with getContent() because it looks like there's just as much effort creating a workaround to get jquery validation working with tinymce. Thoughts on possible solutions?
The following stackoverflow questions should help you on that issue:
validating multiple TinyMCE Editor
Jquery validation form with TinyMCE field who gives no error by empty value
Hi if your are not getting client side validation on form submit time when you are with tinymce try this code
suppose your have two html editor 1 is txtAboutCompanyand 2 is txtProductinfo
this is client side code
<div class="divclass">
#Html.LabelFor(model => model.txtAboutCompany, new { #class = "required" })
#Html.EditorFor(model => model.txtAboutCompany)
<span class="field-validation-error" id="AC" style="margin:9px 0 0 157px;"></span>
</div>
this is jquery
$("#BusinessProfile").click(function () {
var aboutC = $("#txtAboutCompany").val()
var pinfo = $("#txtProductinfo").val();
if (aboutC == "" && pinfo == "") {
$("#AC").append("").val("").html("Please enter about company")
$("#PI").append("").val("").html("Please enter product information")
$("#bpform").valid();
return false;
} else if (aboutC == "") {
$("#PI").append("").val("").html("")
$("#AC").append("").val("").html("Please enter about company")
$("#txtAboutCompany").focus();
$("#bpform").valid();
return false;
} else if (pinfo == "") {
$("#AC").append("").val("").html("")
$("#PI").append("").val("").html("Please enter product information")
$("#txtProductinfo").focus();
$("#bpform").valid();
return false;
}
else {
$("#AC").append("").val("").html("");
$("#PI").append("").val("").html("");
//return true;
$("#bpform").validate();
}
});
you can get your all required validation on form submit time
I know this is not proper way but you can do it .
function tinymceValidation() {
var content = tinyMCE.activeEditor.getContent();
if (content === "" || content === null) {
$("#questionValid").html("<span>Please enter question statement</span>");
} else {
$("#questionValid").html("");
}
}
tinymce.activeEditor.on('keyup', function (e) {
debugger;
tinymceValidation();
});
$(form).submit(function (e) {
tinymceValidation();
});

Categories