I want to validate form. I try to validate it using regexp. When I create event 'click' and bind it to button element, i've faced the problem. When I click on button element under email input shows a message
'Please enter a valid email address. And when I click second time value change to true, but initially value of email input is true(because I check it, below on screen you can see it).
const form = document.querySelector('form')
const emailRegexp = /^[\w.+\-]+#gmail\.com$/g;
const usernameRegexp = /^\w+(?![\b])\w+$/g;
const fail = document.querySelectorAll('div.input_failed');
console.log(emailRegexp.test('fdjfvnjdknv#gmail.com'));
styleButton.addEventListener('click', function(event) {
const testEmail = emailRegexp.test(input[0].value);
if(testEmail) {
fail[0].style.display = 'none';
console.log(true);
}
else {
fail[0].style.display = 'block';
console.log(false);
}
});
main.js:49 true
main.js:59 false
main.js:55 true
main.js:59 false
main.js:55 true
main.js:59 false
main.js:55 true
main.js:59 false
main.js:55 true
main.js:59 false
main.js:55 true
main.js:59 false
main.js:55 true
main.js:59 false
I check the type of this two string and they are both string.Anyway the problem didn't solved. And I don't know what to do.
Regex only for #gmail.com
var emailRegexp = new RegExp(/^[\w.+\-]+#gmail\.com$/,"g");
Regex for email validation
var emailRegexp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
You can also test the regex here: https://regex101.com/
Related
I have multiple input fields and if three fields showing error then focus goes on the last error field.
How to set focus on the first error field and so on. I tried return false; and it is not working. preventDefault() also not working.
This is my js code for the name field and the rest of the field validation is the same as this name field except validation rules.
if (name.length < 1) {
$('#name_error').text(NAME_ERROR);
$('#name').focus();
error = true;
// return false; not working
} else {
var regEx = /^[A-Za-z ]+$/;
var validName = regEx.test(name);
if (!validName) {
$('#name_error').text(INVALID_NAME_ERROR);
$('#name').focus();
error = true;
// return false; not working
} else {
$('#name_error').text('');
error = false;
}
}
Option 1 - Add class to the fields with error and then you can use below code to focus the first error element.
$('.error-class').first().focus()
Option 2 - Create a variable of top of the function and store the ID of the first error field in that. At the end of the validation rules trigger focus for the element ID stored in a variable.
I need to intercept a click on the page and execute some validation logic and let the flow go on.
I have a link:
<a data-link="true">Link</a>
Js to intercept:
$("a[data-link='true'").off("click.link").on("click.link", (event) => this.validate(event));
In validate function I just make some validations and I need to proceed with the request.
How can I intercept the click and If validation it's ok, proceed with the original request ?
Thanks.
Your data selector might do better if it was more generalized:
$(function(){
// Listen for data link in general
$('a[data-link]').on('click',function(e){
// Stop all request
e.preventDefault();
// Get the link href
var hrefPath = $(this).attr('href');
// If the data-link is set to true
if($(this).data('link') === true) {
// Do your validation here, not sure if your validation function
// works or not, but here is where you apply it
var valid = true;
// If failed, set the default path to empty
if(!valid)
hrefPath = false;
// If the path is not empty, go to the default path
if(hrefPath !== false)
window.location = hrefPath;
// Stop
return false;
}
// If the link is not true, just go to the default path
window.location = hrefPath;
});
});
I am having trouble with an if-statement. In this statement i want to check if a checkbox is checked true (or isSelected) then it shall proceed with the instruction to disable a textarea. This part is working fine. But unfortunately if the checkbox is unchecked it still disabling the textarea, but it shouldn't. It should leave the textarea enabled.
function auswahl_bestaetigen(){
tweet = document.getElementById("chk_tweet")
twitter = document.getElementById("twitter")
if (tweet.isSelected = true)
twitter.disabled = true
else if (tweet.isSelected = false)
twitter.disabled = false
}
i hope someone can help me with this problem. Thanks in advance :)
The property to test whether an <input type="checkbox"> is checked is called checked. So your code should be:
if (tweet.checked) {
twitter.disabled = true
} else {
twitter.disabled = false
}
Or even shorter:
twitter.disabled = tweet.checked
Here's a simple demo:
var tweet = document.getElementById('chk_tweet')
var twitter = document.getElementById('twitter')
tweet.addEventListener('change', function () {
twitter.disabled = tweet.checked
});
#twitter[disabled] {
background: grey;
}
<input id="chk_tweet" type="checkbox" />
<textarea id="twitter"></textarea>
https://jsfiddle.net/foxbunny/m4oda3zy/
I am trying to create a custom Dojo ValidationIdBox widget that inherits from ValidationTextBox. My custom widget will add async duplicate ID checking with a back-end server.
I sub-classed dijit.form.ValidationTextBox and modified two methods: isValid() and validate(). However, I can't get the validation to fully work. The widget catches and highlights problems like missing required input. It even catches when there is a duplicate ID (the tooltip appears), but it fails to highlight the field as expected.
I have tried to isolate my problem with a simplified code snippet below. It is mostly the origininal Dojo code with some minor modifications. My general strategy is to let the widget validate as a regular ValidationTextBox, then test for a duplicate ID. I modified isValid() to have two modes: plain validation and validation with uniqueness check. Currently, the uniqueness test intentionally always fails.
In a similar fashion, I modified validate() to do its normal thing, then do some additional processing if normal validation succeeds but the validation with uniqueness test fails. I tried to mirror the same logic as when the ValidationTextBox is in an error state, but the same effects are not mirrored: The 'ID not available' tooltip appears, but the red outline with exclamation mark does not appear.
I examined ValidationTextBox's code, but I cannot figure out how that special styling is triggered... can someone explain how ValidationTextArea works? Specifically I'm not quite sure how this._maskValidSubsetError, aria-invalid, and this.state are used.
(Also sometimes, I want the tooltip to appear, but not the red styling. Like to show when AJAX duplicate ID check request is processing.)
// If ValidationTextBoxValidates
isValid: function(isFocused, requireUnique) {
if (typeof requireUnique === 'undefined') requireUnique = false;
var isValid = this.inherited(arguments);
var isUnique = false;
return (requireUnique ? (isValid && isUnique) : isValid);
},
validate: function(/*Boolean*/ isFocused){
// summary:
// Called by oninit, onblur, and onkeypress.
// description:
// Show missing or invalid messages if appropriate, and highlight textbox field.
// tags:
// protected
var message = "";
var isValid = this.disabled || this.isValid(isFocused);
if(isValid){ this._maskValidSubsetError = true; }
var isEmpty = this._isEmpty(this.textbox.value);
var isValidSubset = !isValid && isFocused && this._isValidSubset();
this._set("state", isValid ? "" : (((((!this._hasBeenBlurred || isFocused) && isEmpty) || isValidSubset) && this._maskValidSubsetError) ? "Incomplete" : "Error"));
this.focusNode.setAttribute("aria-invalid", isValid ? "false" : "true");
if(this.state == "Error"){
this._maskValidSubsetError = isFocused && isValidSubset; // we want the error to show up after a blur and refocus
message = this.getErrorMessage(isFocused);
}else if(this.state == "Incomplete"){
message = this.getPromptMessage(isFocused); // show the prompt whenever the value is not yet complete
this._maskValidSubsetError = !this._hasBeenBlurred || isFocused; // no Incomplete warnings while focused
}else if(isEmpty){
message = this.getPromptMessage(isFocused); // show the prompt whenever there's no error and no text
}
/// Begin custom widget code
if (isValid && !this.isValid(isFocused, true) ) {
isValid = false;
var isValidSubset = !isValid && isFocused && this._isValidSubset();
this._maskValidSubsetError = isFocused && isValidSubset; // we want the error to show up after a blur and refocus
message = 'ID not available';
this.focusNode.setAttribute("aria-invalid", isValid ? "false" : "true");
}
/// End custom widget code
this.set("message", message);
return isValid;
},
might be missing the obvious, hidden amongst a cloud of inline &&|| ;)))))
The point in the blur/keypress mechanism is that the tooltip will only be visible on the box that is currently shown, hence _maskValid
Have you tried this.set("state", this.isUnique() ? "" : "Error"); ??
Widgets are Stateful and the .set might just do the trick, firing an event or publish a topic
This is a validation script
This code runs when the user presses the submit button on a form
It loops thru all mandatory fields (entered in an array) and...
1. checks if the element is hidden
2. if not is it empty?
3. if not is it false? (I use false as a value for non selectable options)
And all this sets a variable to true or false.
// when submitting the registration form
function mandatoryCheck() {
jQuery('.tx-powermail-pi1_formwrap_1723 form.tx_powermail_pi1_form').submit(function(event) {
var success = false;
var element;
jQuery.each(mandatoryFields, function(index, value) {
element = jQuery('#powermaildiv_uid'+value+' input, #powermaildiv_uid'+value+' select')
element.each(function() {
// add class required to all fields
jQuery(this).addClass('required');
// is the element hidden, return true
if(jQuery(this).hasClass('fieldHidden') == true || jQuery(this).is(':disabled')) {
success = true;
} else {
// is the input field empty, return false
if(jQuery(this).val().length === 0) {
success = false;
// is the input field not empty, return true
} else {
// is the input field false, return false
if(jQuery(this).val() == 'disabled') {
success = false;
} else {
success = true;
}
}
}
// For each element add/remove validation class
if(success == false) {
jQuery(this).addClass('validation-failed').removeClass('validation-passed');
} else {
jQuery(this).addClass('validation-passed').removeClass('validation-failed');
}
});
});
// if succes is false, show error message and return false
if(success == false) {
jQuery('#c1799').fadeIn().css('display', 'block');
event.preventDefault();
return false;
} else {
jQuery('#c1799').fadeOut();
}
});
}
It works in firefox, chrome ie9 but not ie 7 or 8.
IE7 or 8 adds classes to the elements all random.
It seems like if I validate a select element it passes but an input field fails
What can be wrong?
Edit:
Here is the page: http://asdf.patrikelfstrom.se/index.php?id=267
Enter 1234 if in the little form that shows up
JS: http://asdf.patrikelfstrom.se/typo3conf/ext/gc_fm/res/js/ShowAndHideFields.js
If you press submit (absenden) the field Türnummer should be green (as it is in chrome, firefox etc.) but in ie7/8 it is red.
If you click on Wähle... (The select box) and choose Wohnung the fields under it becomes enabled and if you press submit now Türnummershould be red since the element is visible and empty.
This seems to work but if you click on the select box again and choose einfamilienhaus.
The fields are disabled and should now be green when submitting but this is not the case in IE7/8.
I think you need to loop through element, as it will be a collection of objects, so you would do...
// is the element hidden, return true
element.each(function() {
if($(this).hasClass('fieldHidden') == true) {
...
})
Well, just to show the point, depends on your code what you need to actually change
Remove the (value="false") from your selects.