I'm trying to create a simple validation method with jQuery, but without a plugin. So I made this code:
(function ($) {
$.fn.validate = function () {
var emailRegex = '^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$';
var error = false;
if ($('#vorname').val() == "") {
$('#vorname').after('<span class="error">Name fehlt</span>');
error = "true";
}
if ($('#nachname').val() == "") {
$('#nachname').after('<span class="error">Name fehlt</span>');
error = "true";
}
if ($('#email').val() == "") {
$('#email').after('<span class="error">Email fehlt</span>');
error = "true";
} else if (!emailRegex.test($('#email').val())) {
$('#email').after('<span class="error">Keine gültige Email</span>');
error = "true";
}
if (error == true) {
return false;
} else {
return;
true;
}
}
})(jQuery);
$(document).ready(function () {
$('#button').click(function () {
$('#button').validate();
});
});
But I'm getting always the message that my regex test isn't a function. What's the issue?
You write:
var emailRegex = '^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$';
You might want to write:
var emailRegex = new RegExp('^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$');
// or simpler
var emailRegex = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/;
Your emailRegex is defined as String.
Define it as regexp like this.
emailRegex = /hogehoge/
Related
I'm trying to create a simple code verification that checks to code value on key up event and while it's checks - it should show a spinner - but when the timeout has ended then it should displays a markup accordingly (invalid or check mark).
Here is the controller
angular.module("app", []);
angular.module("app").controller("MainController", function ($scope, $timeout) {
$scope.searchStr = "";
$scope.arrResults = [];
$scope.valCode = "666666";
$scope.isShowSpinner = false;
$scope.errorMsg = "";
$scope.isSuccess = false;
$scope.checkCode = function () {
let isError = false;
$timeout.cancel(debounce);
if ($scope.codeArr.join("") == $scope.valCode) {
console.log($scope.codeArr.join(""));
}
if ($scope.codeArr.join("").length == 6) {
$scope.isShowSpinner = true;
var debounce = $timeout(function () {
// debugger;
$scope.errorMsg = "";
$scope.isSuccess = false;
if ($scope.codeArr.join("") != $scope.valCode) {
isError = true;
$scope.errorMsg = "Invalid Code";
}
}, 2000);
$timeout(function () {
$scope.isShowSpinner = false;
if ($scope.errorMsg.length) {
$scope.isSuccess = false;
} else {
$scope.isSuccess = true;
}
}, 50);
}
};
angular.element(document).ready(function () {
$(document).ready(function () {
var body = $("body");
$("body input").on("input", function (e) {
let t = $(e.target);
let sib = t.next("input");
if (isNaN(parseInt(this.value))) {
e.preventDefault();
this.value = null;
return false;
} else {
if (!sib || !sib.length) {
sib = body.find("input").eq(0);
}
sib.select().focus();
return true;
}
});
function getSmsValue(e) {
let isError = false;
e.preventDefault();
var debounce = null;
smsCharsArr = [];
$(".sms-input").each(function () {
let smsValue = this.value;
if (!!smsValue && smsValue !== "") {
smsCharsArr.push(smsValue);
$scope.codeArr = smsCharsArr;
}
});
}
body.on("blur", "input", getSmsValue);
});
});
});
Here is the markup of the indications :
<div ng-if="isShowSpinner" class="spinner-border" role="status">
<span class="sr-only">Loading...</span>
</div>
<div ng-if="isSuccess">
<span><i class="fa fa-check"></i></span>
</div>
</div>
<div ng-if="errorMsg.length" class="row">
<h1>{{errorMsg}}</h1>
</div>
So when there are 6 digis - there is a debounce of 2 second to check if the code is correct - while it's checks i want to show the spinner - but when the timeout had ended - i want to hide the spinner and show the results - "invalid" text or "check" icon....
The correct code is 666666 ,
Here is an example
Thanks
I am making a financial report where user choose 2 dates search_date1 and search_date2, and then a monthly report is generated.
I created first a daily report with only one calendar and when it is changed I apply some AJAX script to it and it works correctly:
var myApp = {};
myApp.search_date = "";
document.getElementById('search_date').onchange = function (e) {
if (this.value != myApp.search_date) {
var d = $("#search_date").val();
$.ajax({
...
});
}
}
Now I can't know how to detect if both calendars are changed to apply AJAX script according to their values.
EDIT
Is it correct to do the following:
var myApp = {};
myApp.search_date1 = "";
myApp.search_date2 = "";
document.getElementById('search_date1').onchange = function (e) {
if (this.value != myApp.search_date1) {
var d1 = $("#search_date1").val();
document.getElementById('search_date2').onchange = function (e) {
if (this.value != myApp.search_date2) {
var d2 = $("#search_date2").val();
$.ajax({
...
})
}
});
}
});
try this:
var temp = {
from: null,
to: null
}
document.getElementById('from').onchange = function(e){
temp.from = e.target.value;
goAjax();
}
document.getElementById('to').onchange = function(e){
temp.to = e.target.value;
goAjax();
}
function goAjax(){
if(temp.from && temp.to && new Date(temp.from) < new Date(temp.to)){
//do ajax call
console.log('valid')
}
}
<input type="date" id='from'/>
<br>
<input type="date" id='to'/>
I would have captured the change event for both elements :
$("#search_date1, #search_date2").on('change',function(){
var d1 = $("#search_date1").val();
var d2 = $("#search_date2").val();
$.ajax({...});
});
What you do in your edit may work, but it would be better (and easier) do something like this
var myApp = {};
myApp.original_search_date1 = $("#search_date1").val();
myApp.original_search_date2 = $("#search_date2").val();
myApp.search_date1 = $("#search_date1").val();
myApp.search_date2 = $("#search_date2").val();
document.getElementById('search_date1').onchange = function (e) {
if ($("#search_date1").val() != myApp.search_date1) {
myApp.search_date1 = $("#search_date1").val();
sendAjax();
}
});
document.getElementById('search_date2').onchange = function (e) {
if ($("#search_date2").val() != myApp.search_date2) {
myApp.search_date2 = $("#search_date2").val();
sendAjax();
}
});
function sendAjax() {
if (myApp.original_search_date1 !== myApp.search_date1 &&
myApp.original_search_date2 !== myApp.search_date2) {
$.ajax({
...
});
}
}
Cant you just set a variable to check if its been changed with true/false then run the script if both variables are true.
Something like,
var searchOneToggled = false,
searchTwoToggled = false;
$('#search_date_one').on('input', function() {
searchOneToggled = true;
runYourFunction();
});
$('#search_date_two').on('input', function() {
searchTwoToggled = true;
runYourFunction();
});
function runYourFunction() {
if(searchOneToggled === true && searchTwoToggled === true) {
alert('hello world');
}
}
Here's the HTML button I'm working with:
<b>Other: </b><input type="number" id="AmntValue" data-target-element-id="SubmitAmnt" data-target-parameter="Amnt" onchange="setValueOnTarget(this);' +/* ' enableButton(SubmitAmnt);' */+ '">
<button class="button2" id="SubmitAmnt" type="button" data-redirect-src="https://hub.deltasigmapi.org/donations/donations.aspx?appealid=1989&NumberOfPaymentsDisplay=0&GiftRecurrenceDisplay=0&GiftRecurrence=onetime&GiftAmount=" onclick="disableButton(this); addValueToQueryString(this); redirectPage(this);">Continue To Payment</button>
When someone hits the button but the "Other" text field is blank, it's supposed to not redirect and instead show an error message. Right now the error message displays, but only for a quick moment before it redirects anyway.
Here is my complete JavaScript code:
function setValueOnTarget(sourceElem) {
var targetId = sourceElem.getAttribute('data-target-element-id');
if (targetId) {
var targetElem = document.getElementById(targetId);
if (targetElem) {
var valueToSet;
var parameterToSet;
if (sourceElem.nodeName.toUpperCase() == 'SELECT') {
valueToSet = sourceElem.options[sourceElem.selectedIndex].value;
}
if (sourceElem.nodeName.toUpperCase() == 'INPUT') {
if (sourceElem.type.toUpperCase() == 'NUMBER' || sourceElem.type.toUpperCase() == 'TEXT') {
valueToSet = sourceElem.value;
}
}
targetElem.setAttribute('data-value-set-by-other-element', valueToSet);
parameterToSet = sourceElem.getAttribute('data-target-parameter');
targetElem.setAttribute('data-target-parameter', parameterToSet);
EnableButton(targetElem)
}
}
}
function disableButton(btn) {
btn.disabled = true;
}
function EnableButton(btn) {
btn.disabled = false;
}
function addValueToQueryString(elem) {
var src = elem.getAttribute('data-redirect-src');
var newValue = elem.getAttribute('data-value-set-by-other-element');
var parameter = elem.getAttribute('data-target-parameter');
if (newValue && parameter) {
if (src && newValue && parameter) {
var newSrc;
newSrc = src + newValue;
elem.setAttribute('data-redirect-src', newSrc);
} else {
displayError('Could not find the URL to redirect to');
}
} else {
displayError('No value or parameter has been set. Please set a proper value.');
}
}
function redirectPage(elem) {
var src = elem.getAttribute('data-redirect-src');
window.location = src;
}
function displayError(message) {
var userMessage = document.getElementById('userMessage');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'red';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
function displaySuccess(message) {
var userMessage = document.getElementById('userMessage1');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'green';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
I'm not sure if something's wrong with the code I put in the button or in the JavaScript.
Disable button by default
The button should be disabled by default, and should only be enabled when the expected input value is detected. It appears you already have a mechanism for this in your example, but you have some impediments to overcome first:
button should be disabled by default. Do this in the HTML:<button disabled …>Continue To Payment</button>
input's onchange handler should just call setValueOnTarget(), because this function already calls EnableButton(). In the HTML:<input onchange="setValueOnTarget(this);" … >
Remove the call to redirectPage() from the button's onclick handler and move it into addValueToQueryString() after you have assigned a value to newSrc.
Add a call to EnableButton() after you call displayError() in cases where you want to allow the user to modify the input and try again.
For example:
function setValueOnTarget(sourceElem) {
var targetId = sourceElem.getAttribute('data-target-element-id');
if (targetId) {
var targetElem = document.getElementById(targetId);
console.log(targetElem);
if (targetElem) {
var valueToSet;
var parameterToSet;
if (sourceElem.nodeName.toUpperCase() == 'SELECT') {
valueToSet = sourceElem.options[sourceElem.selectedIndex].value;
}
if (sourceElem.nodeName.toUpperCase() == 'INPUT') {
if (sourceElem.type.toUpperCase() == 'NUMBER' || sourceElem.type.toUpperCase() == 'TEXT') {
valueToSet = sourceElem.value;
}
}
targetElem.setAttribute('data-value-set-by-other-element', valueToSet);
parameterToSet = sourceElem.getAttribute('data-target-parameter');
targetElem.setAttribute('data-target-parameter', parameterToSet);
EnableButton(targetElem);
}
}
}
function disableButton(btn) {
btn.disabled = true;
}
function EnableButton(btn) {
btn.disabled = false;
}
function addValueToQueryString(elem) {
var src = elem.getAttribute('data-redirect-src');
var newValue = elem.getAttribute('data-value-set-by-other-element');
var parameter = elem.getAttribute('data-target-parameter');
if (newValue && parameter) {
if (src && newValue && parameter) {
var newSrc;
newSrc = src + newValue;
elem.setAttribute('data-redirect-src', newSrc);
redirectPage(elem);
} else {
displayError('Could not find the URL to redirect to');
}
} else {
displayError('No value or parameter has been set. Please set a proper value.');
EnableButton(elem);
}
}
function redirectPage(elem) {
var src = elem.getAttribute('data-redirect-src');
window.location = src;
}
function displayError(message) {
var userMessage = document.getElementById('userMessage');
userMessage.innerHTML = message;
userMessage.style.backgroundColor = 'red';
userMessage.style.color = 'white';
userMessage.style.display = 'block';
}
<b>Other: </b>
<input
type="number"
id="AmntValue"
data-target-element-id="SubmitAmnt"
data-target-parameter="Amnt"
onchange="setValueOnTarget(this);">
<button
disabled
class="button2"
id="SubmitAmnt"
type="button"
data-redirect-src="https://hub.deltasigmapi.org/donations/donations.aspx?appealid=1989&NumberOfPaymentsDisplay=0&GiftRecurrenceDisplay=0&GiftRecurrence=onetime&GiftAmount="
onclick="disableButton(this); addValueToQueryString(this);">Continue To Payment</button>
<div id="userMessage"></div>
I've made a login form that will check that username and password are valid or not.
Everything is good, until I press Login.
After press login button it said that username and password is wrong although it is not.
How could I fix this? I think it is about return in userCheck() and pwdCheck() functions.
Here is my form
<form name="loginForm" id="loginForm">
<input type="text" id="user" name="user" onfocus="userFocus()" onblur="userBlur()">
<span id="userWarn" class="warnSpan">Username is required.</span>
<input type="text" id="pwd" name="pwd" onfocus="pwdFocus()" onblur="pwdBlur()">
<span id="pwdWarn" class="warnSpan">Username is required.</span>
</form>
Here is the javascript:
var pwdElem = document.getElementById("pwd");
var pwdVal = document.getElementById("pwd").value;
var pwdWarn = document.getElementById("pwdWarn");
var pwdLen = pwdVal.length;
var pwdCheck = pwdCheck();
var userElem = document.getElementById("user");
var userVal = document.getElementById("user").value;
var userWarn = document.getElementById("userWarn");
var userLen = userVal.length;
var userCheck = userCheck();
function userFocus()
{
userElem.style.backgroundColor = "#ccffff";
userElem.style.border = "1px inset #00ffff";
userElem.style.color = "#00ffff";
}
function userBlur()
{
var userLenx = document.getElementById("user").value.length;
if (userLenx != 0)
{
userOk();
}
else
{
userError();
}
}
function pwdFocus()
{
pwdElem.style.backgroundColor = "#ccffff";
pwdElem.style.border = "1px inset #00ffff";
pwdElem.style.color = "#00ffff";
}
function pwdBlur()
{
var pwdLenx = document.getElementById("pwd").value.length;
if (pwdLenx >= 8)
{
pwdOk();
}
else
{
pwdError();
}
}
function userCheck()
{
var userLenx = document.getElementById("user").value.length;
if (userLenx != 0)
{
return "ok";
}
else
{
return "error";
}
}
function pwdCheck()
{
var pwdLenx = document.getElementById("pwd").value.length;
if (pwdLen >= 8)
{
return "ok";
}
else
{
return "error";
}
}
function userError()
{
userElem.style.backgroundColor = "#ffcccc";
userElem.style.border = "1px inset #ff0000";
userElem.style.color = "#ff0000";
userWarn.style.visibility = "visible";
}
function pwdError()
{
pwdElem.style.backgroundColor = "#ffcccc";
pwdElem.style.border = "1px inset #ff0000";
pwdElem.style.color = "#ff0000";
pwdWarn.style.visibility = "visible";
}
function userOk()
{
userElem.style.backgroundColor = "#ddffdd";
userElem.style.border = "1px outset #00bb00";
userElem.style.color = "#00bb00";
userWarn.style.visibility = "hidden";
}
function pwdOk()
{
pwdElem.style.backgroundColor = "#ddffdd";
pwdElem.style.border = "1px outset #00bb00";
pwdElem.style.color = "#00bb00";
pwdWarn.style.visibility = "hidden";
}
function errorForm()
{
if (userCheck=="error"&&pwdCheck=="error")
{
userError();
pwdError();
}
else if (userCheck=="error"&&pwdCheck=="ok")
{
userError();
}
else if (userCheck=="ok"&&pwdCheck=="error")
{
pwdError();
}
else
{
alert("Sorry, an error occured.\n\nPlease refresh page and try again.");
}
}
function loginSubmit()
{
if (userCheck=="ok"&&pwdCheck=="ok")
{
userOk();
pwdOk();
loginForm.submit();
}
else
{
errorForm();
}
}
Here is the Jsbin
Please help, I am new to coding!
The issue with you code seems to be in the function loginSubmit(). It should read as follows:
function loginSubmit()
{
if (userCheck()=="ok"&&pwdCheck()=="ok") // <--change here
{
userOk();
pwdOk();
loginForm.submit();
}
else
{
errorForm();
}
}
The two variables you were referring to (userCheck and pwdCheck) are initialised as soon as the page loads. This means they will represent the state of the login and password fields when the page loads. Since these fields are empty when the page loads, the loginSubmit() function will always show the error. Hope this helps.
You are returning a string from the function, but you aren't using it for anything...
Short example
function getString() {
return "A string";
}
// I don't even store the string...
getString();
So to fix it, use the string that is returned
// Store it
var example = getString();
// Use it
alert(example);
Below code will do the validation which you are trying
function validate()
{
if(trim(document.frmLogin.sUserName.value)=="")
{
alert("Username is required.");
document.frmLogin.sUserName.focus();
return false;
}
else if(trim(document.frmLogin.sPwd.value)=="")
{
alert("Please Enter a Password");
document.frmLogin.sPwd.focus();
return false;
}
}
You appear to have a problem with the way you are trying to call userCheck, pwdCheck, etc.
You are missing the parentheses, which means you are comparing the function itself (i.e. not the result of calling the function) with a string.
your comparisons should look something like this once you've added the parentheses
if (userCheck()=="error"&&pwdCheck()=="error")
I am building some validation but when I submit correct input it still shows as not valid, can't quite figure out where I'm going wrong!
The function works with invalid input but not with valid input
Javascript/jQuery
(function(){
var form = '.contact-form',
alert = '.alert',
fieldWrap = '.control-group',
errorMsg = '.error-message',
error = 'error',
show = 'show',
hide = 'hide';
var textField = function(){$(field).val() !== (regEx); return false};
var select = function(){$(field + ' option:selected').val() === regEx; return false};
var validate = function(ifParam,field,regEx,e){
if(ifParam()){
$(field).parents(fieldWrap).addClass(error).find(errorMsg).addClass(show);
return false;
}
else{
$(field).parents(fieldWrap).removeClass(error).find(errorMsg).addClass(hide);
return true;
}
};
var valid = function(e){
validate(textField,'#first-name' ,/^[a-zA-Z]$/,e);
validate(textField,'#last-name' ,/^[a-zA-Z]$/,e);
validate(textField,'#contact-number' ,/^[a-zA-Z]$/,e);
validate(textField,'#email' ,/^[a-zA-Z]$/,e);
validate(textField,'#landline-number',/^[a-zA-Z]$/,e);
validate(textField,'#postcode' ,/^[a-zA-Z]$/,e);
validate(select ,'#title' ,'select',e);
return true;
};
$(document).on('submit',form,function(e){
if(!valid()){
$(alert).addClass(show);
e.preventDefault();
e.stopPropagation();
}
else{
$(this).unbind('submit').submit();
}
});
})();